当ThreadA中的System.out.println未被注释时,它运行正常。
竞争条件是否与System.out.println相关
对于刷新到系统控制台,需要时间并且运行正常。
什么可以解决这个问题顺利运行而不中断
package com.test.concurrency;
class ThreadA extends Thread{
private int sum = 0;
@Override
public void run(){
synchronized (this) {
//System.out.println();
for(int i = 0; i<100 ;i++){
sum += i;
}
notify();
}
}
public int getSum(){
return sum;
}
}
public class WaitNNotify {
public static void main(String[] args) {
ThreadA t= new ThreadA ();
t.start();
System.out.println("Waiting for ThreadA to complete..."+Thread.currentThread().getName());
synchronized (t) {
try{
t.wait();
System.out.println("Finally the Thread is notified ... "+t.getSum());
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:1)
您应该使用join
而不是wait-notify
用于您的方案,以下是示例实现:
class ThreadA extends Thread {
private int sum = 0;
@Override
public void run() {
System.out.println();
for (int i = 0; i < 100; i++) {
sum += i;
}
}
public int getSum() {
return sum;
}
}
public class WaitNNotify {
public static void main(String[] args) {
ThreadA t = new ThreadA();
t.start();
System.out.println("Waiting for ThreadA to complete..."+ Thread.currentThread().getName());
try {
t.join();
System.out.println("Finally the Thread is completed ... "+ t.getSum());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
从synchronized
移除notify()
阻止和ThreadA
方法调用,并将wait()
替换为join()
:
public void run(){
//System.out.println();
for(int i = 0; i<100 ;i++){
sum += i;
}
}
和
t.join();