【发布时间】:2013-09-02 11:24:13
【问题描述】:
所以在这里我编写了三个简单的类来检查多个线程在 java 中是如何工作的,但是每次运行时它们都会产生不同的结果。代码如下:
public class Accum {
private static Accum a = new Accum();
private int counter = 0;
private Accum(){}
public static Accum getAccum(){
return a;
}
public void updateCounter(int add){
counter+=add;
}
public int getCount(){
return counter;
}
}//end of class
public class ThreadOne implements Runnable {
Accum a = Accum.getAccum();
public void run() {
for(int x=0; x<98; x++){
//System.out.println("Counter in TWO "+a.getCount());
a.updateCounter(1000);
try{
Thread.sleep(50);
}catch(InterruptedException ex){}
}
System.out.println("one " + a.getCount());
}
}//end of class
public class ThreadTwo implements Runnable{
Accum a = Accum.getAccum();
public void run() {
for(int x=0; x<99; x++){
//System.out.println("counter in Two "+a.getCount());
a.updateCounter(1);
try{
Thread.sleep(50);
}catch(InterruptedException ex){}
}
System.out.println("two "+a.getCount());
}
public class TestThreaad {
public static void main(String[]args){
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
Thread one = new Thread(t1);
Thread two = new Thread(t2);
one.start();
two.start();
}
}end of class
所以预期的结果是:一个98098,两个98099,但结果结果只是无法预测,有时是78000或81000,我不知道..
但如果我添加一些代码来打印一行当前计数值,最终结果将是正确的..
实在不知道怎么回事,竟然在ThreadOne和ThreadTwo,run()方法中加上了关键字synchronized,问题依旧……
我已经研究了 3 个月的 java,这是我遇到过的最难以捉摸的问题......所以提前感谢任何人可以帮助我理解多线程的基本点......
【问题讨论】:
-
这就是为什么 Java 有
synchronized。
标签: java multithreading