为什么我的synchronized依然不能保持线程安全?

package com.imooc.concurrent.test;


public class Test {

public static void main(String[] args)  {

        final aquryI a = new aquryI();

    while(true){   

        new Thread("Thread A") {

            public void run() {

                a.read();

                a.write();

                a.read();

                try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

            };

        }.start();

         

         

        new Thread("Thread B") {

            public void run() {

                a.read();             

                try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}       

            };

        }.start();

        System.out.println("\n");

        try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }  

}

}


class aquryI {

    

private volatile static int i;     

    

public synchronized void write(){

           i +=10;        

           System.out.println(Thread.currentThread().getName());

        

    }

    public synchronized void read(){

    System.out.println(Thread.currentThread().getName());

    System.out.println(i);

    }

}


运行结果如下:

Thread A

0

Thread A

Thread A

10



Thread B

10



Thread A

10

Thread A

Thread A

20

Thread B

20



Thread A

20

Thread A

Thread A

30

Thread B

30



Thread A

30

Thread A

Thread A

40

Thread B

40



Thread A

40

Thread A

Thread A

50

Thread B

50



Thread A

50

Thread A

Thread A

60

Thread B

60



Thread A

60

Thread B

60

Thread A

Thread A

70



Thread A

70

Thread A

Thread A

80

Thread B

80



Thread A

80

Thread A

Thread A

90

Thread B

90



Thread A

90

Thread B

90

Thread A

Thread A

100

.....

Thread A

120

Thread B

120

Thread A

Thread A

130



Thread A

130

Thread B

130

Thread A

Thread A

140



Thread A

140

Thread A

Thread A

150

Thread B

150



Thread A

150

Thread A

Thread A

160

Thread B

160



Thread B

160

Thread A

160

Thread A

Thread A

170

虽然大部分时候可以保证  但是有时候还是会出现A B交替运行的现象 这是为什么?

阿Dine
浏览 1211回答 0
0回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java