相关疑难解决方法(0)

Java线程:等待并通知方法

我有一个调用该wait方法的线程,只有当notify从其他类调用该方法时才能唤醒:

 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码synchronizedmain,如果块中,如果ThreadA不执行第一个而不是另一个同步块执行并完成,则ThreadA执行其synchronized块和调用wait …

java multithreading notify wait

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

multithreading ×1

notify ×1

wait ×1