各位大神,本人java小菜鸟。学习java遇到一点问题,下面的代码中,已经使用了join方法,为什么显示的结果不是1000呢?请前辈指教!
public class JoinThread extends Thread {
public static volatile int n=0;
public void run(){
for(int i=0;i<10;i++,n++){
try{
sleep(2);
}catch(Exception e){}
}
}
public static void main(String args[])throws Exception{
Thread[] threads=new Thread[100];
for(int i=0;i<threads.length;i++)
threads[i]=new JoinThread();
for(int i=0;i<threads.length;i++)
threads[i].start();
for(int i=0;i<threads.length;i++)
threads[i].join();
System.out.println("n="+JoinThread.n);
}
}
for(int i=0;i<threads.length;i++)
threads[i].start(); //这里所有线程都启动了,run方法也没有加锁。会有同时多个线程同时访问n,引起脏数据。
for(int i=0;i<threads.length;i++)
threads[i].join(); //这里join只是起到等上面线程执行完了在打印n,但上面n值已经不对了,再等也没用。
System.out.println("n="+JoinThread.n);
解决方法, 增加synchronized
public synchronized void run(){
当然,也可以把锁粒度减小。
n是类变量,共有100个线程,每个线程加10,so 100*10=1000
http://blog.csdn.net/evankaka/article/details/44153709
join是Thread类的一个方法,启动线程后直接调用,即join()的作用是:“等待该线程终止”,这里需要理解的就是该线程是指的主线程等待子线程的终止。也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。
1.有线程没跑完.
2.再就是我看到一个关键字volatile,会不会有影响。
http://blog.csdn.net/gao_chun/article/details/45095995
join只是等待线程结束,但是你d 多个线程访问共享变量并没有加锁,所以导致线程对n的加值并不是一个一的递增,这样最终数据是未知的。