为什么i ++不是原子的?
为什么i++
Java中没有原子?
为了更深入地了解Java,我试图计算线程循环执行的频率。
所以我用了一个
private static int total = 0;
在主要班级。
我有两个主题。
线程1:打印 System.out.println("Hello from Thread 1!");
线程2:打印 System.out.println("Hello from Thread 2!");
并且我计算由线程1和线程2打印的线。但是线程1的线+线程2的线与打印出的总线数不匹配。
这是我的代码:
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.logging.Level;import java.util.logging.Logger;public class Test { private static int total = 0; private static int countT1 = 0; private static int countT2 = 0; private boolean run = true; public Test() { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); newCachedThreadPool.execute(t1); newCachedThreadPool.execute(t2); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } run = false; try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } System.out.println((countT1 + countT2 + " == " + total)); } private Runnable t1 = new Runnable() { @Override public void run() { while (run) { total++; countT1++; System.out.println("Hello #" + countT1 + " from Thread 2! Total hello: " + total); } } }; private Runnable t2 = new Runnable() { @Override public void run() { while (run) { total++; countT2++; System.out.println("Hello #" + countT2 + " from Thread 2! Total hello: " + total); } } }; public static void main(String[] args) { new Test(); }}
缥缈止盈
四季花海
守着星空守着你
相关分类