阅读背景:

2没有synchronized关键字的线程访问共享资源,仍然可以正常工作

来源:互联网 
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;   



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: