返回信息流我尝试对一个static变量i进行i++自增操作,使用了Executors.newCachedThreadPool()来运行1000个线程来操作,思路是每个线程对i进行一次i++,最终应该输出i=1000。这里发现我的方法只有是静态方法时才能实现最终结果是1000的目标 public synchronized static void func2(),非静态的方法public synchronized void func2()不行。有人知道为啥吗?
这是一条镜像帖。来源:北邮人论坛 / java / #64659同步于 2020/10/14
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
尝试使用锁实现多线程对单一变量自增的问题
yuanxiaowu
2020/10/14镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
public synchronized static void func2(){
i++;
}
public static void main(String[] args){
// SynchronizedExample e1 = new SynchronizedExample(0);
// SynchronizedExample e2 = new SynchronizedExample(1);
// ExecutorService executorService = Executors.newCachedThreadPool();
// executorService.execute(() -> e1.func1());
// executorService.execute(() -> e2.func1());
// executorService.shutdown();
ExecutorService executorService= Executors.newCachedThreadPool();
for (int j=0;j<1000;j++){
executorService.execute(()->new SynchronizedExample(1).func2());
}
try {
Thread.sleep(2000);
}catch (Exception e){
}
System.out.println(SynchronizedExample.i);
executorService.shutdown();
}
不使用静态方法时,你锁的是每一个new出来的对象,一共有1000把锁。使用静态方法时,你锁的是SynchronizedExample这个对象,只有1把锁。自己感受下