相关疑难解决方法(0)

为什么i ++不是原子的?

为什么i++Java中没有原子?

为了更深入地了解Java,我试图计算线程循环执行的频率.

所以我用了一个

private static int total = 0;
Run Code Online (Sandbox Code Playgroud)

在主要班级.

我有两个主题.

  • 线程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 Code Online (Sandbox Code Playgroud)

java concurrency multithreading

94
推荐指数
5
解决办法
2万
查看次数

标签 统计

concurrency ×1

java ×1

multithreading ×1