यही वजह है कि i++
जावा में परमाणु नहीं है?
जावा में थोड़ा गहरा होने के लिए मैंने यह गिनने की कोशिश की कि थ्रेड्स में लूप कितनी बार निष्पादित होता है।
इसलिए मैंने ए
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
?