Reputation: 416
When I try to run the below code, the code does not enter into either the block with wait() nor the block with notifyAll(). However, the result of the program is "A B" or "B A". I do not understand what was I missing in the program.
public class threads1 extends Thread {
static Object obj = new Object();
public threads1(String str) {
super(str);
}
public void run() {
try {
waitforsignal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void waitforsignal() throws InterruptedException {
synchronized (obj) {
System.out.println(Thread.currentThread().getName());
while (Thread.currentThread().getName() == "A") {
System.out.println("into wait");
obj.wait();
}
if ((Thread.currentThread().getName() == "B")) {
System.out.println("had notified");
obj.notifyAll();
}
}
}
public static void main(String... strings) throws InterruptedException {
Thread t1 = new threads1("A");
Thread t2 = new threads1("B");
t1.start();
t2.start();
}
}
Upvotes: 0
Views: 56
Reputation: 328608
It has nothing to do with threads: you are comparing strings with ==
instead of equals
.
Once you have fixed that, note that for thread t1
:
Thread.currentThread().getName().equals("A")
will always be true, so your program will never finish...
Upvotes: 1