为什么i++Java中没有原子?
为了更深入地了解Java,我试图计算线程循环执行的频率.
所以我用了一个
private static int total = 0;
Run Code Online (Sandbox Code Playgroud)
在主要班级.
我有两个主题.
System.out.println("Hello from Thread 1!");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 Code Online (Sandbox Code Playgroud)