题目描述
在学习多线程的知识,下面的代码跑出的结果与预想的不一致,看不明白问题出在哪里,麻烦大家帮忙看看
题目来源及自己的思路
我想的是程序结束后staticv的值是个整数200000,但是每次结果都在19xxxxxxx,离的很近,又不像同步出了问题,不知是哪里出了问题,另外代码注释标注为#的位置,foo被synchronized标志,那同步的是SyncObj的实例对象而不是SyncObjc.class,明明是两个实例对象在被调用没有加同步,我以为volatile没加上去结果是错误的,但执行的结果好像没区别,为什么?我不清楚我的理解哪里出了问题,请大家多多指教,谢谢。
相关代码
package concurrency;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SynchronizedTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
SyncObj obj1 =new SyncObj();
SyncObj obj2 =new SyncObj();
CountDownLatch countDownLatch = new CountDownLatch(20);
for(int i=0;i<10;i++) {
executor.execute(new TT(obj1,countDownLatch));
executor.execute(new TT(obj2,countDownLatch));
}
countDownLatch.await();
System.out.println("result----------------------"+SyncObj.staticv);
}
}
class SyncObj {
public static volatile int staticv = 0; //######volatile是不是可有可无?
public synchronized void foo() {
for(int i=0;i<1000;i++) {
System.out.println(staticv);
staticv++;
}
}
}
class TT implements Runnable{
public CountDownLatch countDownLatch;
public SyncObj obj;
public TT( SyncObj obj,CountDownLatch countDownLatch) {
this.obj=obj;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
for(int i=0;i<100;i++) {
obj.foo();
}
countDownLatch.countDown();
}
}
添加回答
举报
0/150
提交
取消