所以在这里我写了三个简单的类来检查多个线程在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,问题依旧……
我已经研究了 Java 3 个月,这是我遇到过的最难以捉摸的问题......所以提前感谢任何人可以帮助我理解多线程的基本点......