เหตุใด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();
    }
}
AtomicIntegerล่ะ?