volatileテスト

3847 ワード

直接コード:
public class Test implements Runnable{ 
    //  volatile  
    private boolean asleep;    
    // volatile  
    //    private volatile boolean asleep;

    public void run() {
        while (!asleep){
            countSheep();
        }
    }

    private void countSheep(){
        //  yield sleep , volatile, , , , 
//                Thread.yield();
//        try {
//            Thread.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    public void setAsleep(){
        this.asleep = true;
    }

    public static void main(String[] args){

        int i = 0;

        while (i<1000){

            Test test = new Test();
            Thread thread1 = new Thread(test);
            thread1.start();
            Thread thread2 = new Thread(new Sleep(test,thread1));
            thread2.start();
            while (thread1.isAlive()||thread2.isAlive());
            System.out.println(i);
            i++;
        }

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("start success");
    }


}
class Sleep implements Runnable{
    private Test test;

    private Thread countSheepThread;
    public Sleep(Test test,Thread thread){
        this.test = test;
        this.countSheepThread = thread;
    }

    public void run() {
        test.setAsleep();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(countSheepThread.isAlive()){
            System.out.println(" ");
        }

    }
}

パラメータに-serverを付けなくてもエラー、jdkバージョンは1.8.0_144,ここでは『java同時プログラミング開発実戦』で述べたのとは異なり,問題を残す.