From 43124b51cc72874820216501d4679b426cc4b148 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 10 Dec 2024 13:26:01 +0100 Subject: [PATCH] added ex H1 --- .../ex_h/TestThreadWithDeadlock.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/exercicses/ex_h/TestThreadWithDeadlock.java diff --git a/src/exercicses/ex_h/TestThreadWithDeadlock.java b/src/exercicses/ex_h/TestThreadWithDeadlock.java new file mode 100644 index 0000000..12f3848 --- /dev/null +++ b/src/exercicses/ex_h/TestThreadWithDeadlock.java @@ -0,0 +1,43 @@ +package exercicses.ex_h; + +public class TestThreadWithDeadlock { + public static Object Lock1 = new Object(); + public static Object Lock2 = new Object(); + + public static void main(String args[]) { + ThreadDemo1 T1 = new ThreadDemo1(); + ThreadDemo2 T2 = new ThreadDemo2(); + T1.start(); + T2.start(); + } + + private static class ThreadDemo1 extends Thread { + public void run() { + synchronized (Lock1) { + System.out.println("Thread 1: Holding lock 1..."); + try { + Thread.sleep(10); + } catch (InterruptedException e) {} + System.out.println("Thread 1: Waiting for lock 2..."); + synchronized (Lock2) { + System.out.println("Thread 1: Holding lock 1 & 2..."); + } + } + } + } + private static class ThreadDemo2 extends Thread { + public void run() { + synchronized (Lock1) { + System.out.println("Thread 2: Holding lock 1..."); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + System.out.println("Thread 2: Waiting for lock 2..."); + synchronized (Lock2) { + System.out.println("Thread 2: Holding lock 1 & 2..."); + } + } + } + } +}