public class Worker {
private int count = 0; //shared resource
public static void main(String[] args) {
Worker w = new Worker();
w.doWork();
}
public void doWork() {
Thread thread1 = new Thread(new Runnable() { //Thread incrementing count 10000 times
public void run() {
for (int i = 0; i < 10000; i++) {
count++; //Not Atomic operation
}
}
});
Thread thread2 = new Thread(new Runnable() { //Thread incrementing count 10000 times
public void run() {
for (int i = 0; i < 10000; i++) {
count++; //Not Atomic operation
}
}
});
thread1.start();
thread2.start();
try {//halts main thread so that both thread race to increment count
thread1.join();
thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count is: " + count);
}
}
public class Worker {
private int count = 0;