1. 程式人生 > >java並發編程實戰第一章

java並發編程實戰第一章

程序 thread format java gin eight num over png

線程不安全代碼測試
    private static class UnsafeSequence {
        private int value;

        public int getNext() {
            return value++;
        }
    }

使用兩個線程分別調用上面的getNext方法1000次,出現了一次線程不安全的情況,在轉出的結果中有兩個1311:

技術分享圖片 圖片.png

原因分析,與書上說的一致:

技術分享圖片 圖片.png


完整的代碼

import java.io.PrintWriter;
import java.util.concurrent.CountDownLatch;

/**
 * Created by luohao07 on 2018/1/2.
 */
public class UnsafeSequenceTest {

    public static void main(String[] args) throws Exception{
        UnsafeSequence unsafeSequence = new UnsafeSequence();
        PrintWriter out = new PrintWriter("out.txt");
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    out.println(unsafeSequence.getNext() + " T1");
                }
                countDownLatch.countDown();
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    out.println(unsafeSequence.getNext()+" T2");
                }
                countDownLatch.countDown();
            }
        }.start();

        countDownLatch.await();
        out.flush();
        out.close();
    }

    private static class UnsafeSequence {
        private int value;

        public int getNext() {
            return value++;
        }
    }
}

Timer執行定時任務
public class TimerTest {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("invoke....");
            }
        }, new Date(System.currentTimeMillis() + 5000));
    }
}

程序啟動後5秒輸出invoke....

java並發編程實戰第一章