kinda new to Threads.
I have 2 Threads and want them to alternately use a method. So Thread 1 does the method, then waits. Then Thread 2 wakes Thread 1 and does the method. Then Thread 1 wakes Thread 2 and does the method etc. But somehow I got a deadlock and I don't understand why.
public class NewT extends Thread{
public void print(NewT x)
{
synchronized(this)
{
System.out.println("x"+x);
notifyAll();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run()
{
for(int i=0;i<10;i++)
{
print(this);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
NewT one = new NewT();
NewT two = new NewT();
one.start();
two.start();
}
}
As the synchronized is on this each thread is locking its own object, and there is actually no synchronization; and they are waiting an event that will never come.
UPDATE:
As someone noted, using a common lock object is not enough because both threads will end up waiting.
Here is a solution:
private static Object lock = new Object();
private static NewT previous;
public static void print(NewT x) throws InterruptedException
{
synchronized(lock) {
while (previous == x) {
lock.wait();
}
System.out.println("x"+ x);
previous = x;
lock.notifyAll();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With