Java threads: wait and notify methods

2019-01-12 07:29发布

I have a thread that calls the wait method and can only be awoken when the notify method called from some other class:

 class ThreadA {
     public static void main(String [] args) {
         ThreadB b = new ThreadB();
         b.start();

         synchronized(b) {
             try {
                 System.out.println("Waiting for b to complete...");
                 b.wait();
             } catch (InterruptedException e) {}
             System.out.println("Total is: " + b.total);
         }
     }
 }

class ThreadB extends Thread {
    int total;
    public void run() {
        synchronized(this) {
            for(int i=0;i<100;i++) {
                total += i;
            }
            notify();
        }
    }
}

In the above code if the synchronized block in main, if the ThreadA does not execute first and instead the other synchronization block executing and completes to completion, then ThreadA executes its synchronized block and calls wait, what is going to happen and how it will be notified again?

7条回答
你好瞎i
2楼-- · 2019-01-12 08:13

Why to make that complex ? Just use join() function of Thread.

ThreadB b = new ThreadB();
b.start();
b.join();
// now print b.total
查看更多
登录 后发表回答