我得到了跟随片段的竞争条件

时间:2014-01-16 14:02:00

标签: java multithreading

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


}

}

2 个答案:

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