Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to let 2 Thread alternating use a method

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();




}

}
like image 260
Stockfish Avatar asked May 20 '26 02:05

Stockfish


1 Answers

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();
    }
}
like image 106
Maurice Perry Avatar answered May 22 '26 16:05

Maurice Perry