简体   繁体   中英

correct approach for 2 threads alternatively printing numbers

I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?

Main Class

public class MyMain {
public static void main(String[] args) {
MyThread1 obj = new MyThread1();

    Thread thread1 = new Thread(obj);
    Thread thread2 = new Thread(obj);

    thread1.setName("t1");
    thread2.setName("t2");

    thread1.start();
    thread2.start();
}
}

Thread Class

public class MyThread1 implements Runnable{
    int i = 0;
    @Override
    public synchronized void run() {
        while(i<10)
        {
            if(i%2==0)
            {   
                try{
                    notify();
                    System.out.println(Thread.currentThread().getName()+" prints "+i);
                    i++;
                    wait();

                 }catch(Exception e){ e.printStackTrace(); }
            }else
            {
                try{
                    notify();
                    System.out.println(Thread.currentThread().getName()+" prints "+i);
                    i++;
                    wait();
                }catch(Exception e){ e.printStackTrace(); }
            }
        }
    }
}

Can there be a better usage of wait() and notify() instead of using it in both the if conditions?

Since there you have some code repetition I'd just go with something like:

while(true) {
    //If it's not my turn I'll wait.
    if(i%2==0) wait();

    // If I've reached this point is because: 
    // 1 it was my turn OR 2 someone waked me up (because it's my turn)
    System.out.println(Thread.currentThread()": "+i);
    i++; // Now is the other thread's turn
    // So we wake him up
    notify();
}

Also, be very careful with monitor's behaviour. (Thread waiting/notifying queues).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM