I am learning synchronization in Java. I know this is a very basic question, but I can’t figure it out.
I have class which contains 2 different objects and 2 Threads.
class MyThreads {
public final static Object den = new Object();
public final static Object ada = new Object();
public static Thread t1 = new Thread() {
public void run() {
System.out.println("Thread 1 den");
System.out.println("Thread 1 ada");
}
};
public static Thread t2 = new Thread() {
public void run() {
System.out.println("Thread 2 den");
System.out.println("Thread 2 ada");
}
};
}
After execute this code:
MyThreads.t1.start();
MyThreads.t2.start();
I should get:
Thread 1 den
Thread 2 den
Thread 1 ada
Thread 2 ada
I am struggling here. I don’t understand how thread 1 can awake thread 2.
public static Thread t1 = new Thread() {
public void run() {
System.out.println("Thread 1 den");
synchronized (den) {
try {
den.notifyAll();
den.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public static Thread t2 = new Thread() {
public void run() {
synchronized (ada){
ada.wait();
// How to awake it?
}
}
};
I will be thankful for any advice!
>Solution :
In order to achieve the desired output where "Thread 1 den" is printed before "Thread 2 den", and "Thread 1 ada" is printed before "Thread 2 ada", you can use wait() and notifyAll() methods to synchronize the execution of the threads. Here’s an updated version of your code:
class MyThreads {
public final static Object den = new Object();
public final static Object ada = new Object();
public static Thread t1 = new Thread() {
public void run() {
System.out.println("Thread 1 before Thread 2");
synchronized (den) {
try {
den.wait(); // Wait until den is notified
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 1 den");
synchronized (ada) {
ada.notifyAll(); // Notify ada to wake up Thread 2
}
}
};
public static Thread t2 = new Thread() {
public void run() {
synchronized (den) {
den.notifyAll(); // Notify den to wake up Thread 1
}
synchronized (ada) {
try {
ada.wait(); // Wait until ada is notified
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 2 ada");
}
};
}
In the updated code, the t1 thread first enters a synchronized block on den and calls den.wait(). This causes t1 to wait until it is notified by another thread. Meanwhile, t2 thread is executed and it enters a synchronized block on den and calls den.notifyAll(), which wakes up the waiting t1 thread.
After t1 is awakened, it prints "Thread 1 den". Then, it enters a synchronized block on ada and calls ada.notifyAll(), which wakes up the waiting t2 thread.
Finally, t2 is awakened and it prints "Thread 2 ada".
By using wait() and notifyAll() methods along with synchronized blocks, you can control the order of execution between the threads and achieve the desired output.