为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

阿Dine 2018-08-05 11:01:04
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 A0Thread AThread A10Thread B10Thread A10Thread AThread A20Thread B20Thread A20Thread AThread A30Thread B30Thread A30Thread AThread A40Thread B40Thread A40Thread AThread A50Thread B50Thread A50Thread AThread A60Thread B60Thread A60Thread B60Thread AThread A70Thread A70Thread AThread A80Thread B80Thread A80Thread AThread A90Thread B90Thread A90Thread B90Thread AThread A100.....Thread A120Thread B120Thread AThread A130Thread A130Thread B130Thread AThread A140Thread A140Thread AThread A150Thread B150Thread A150Thread AThread A160Thread B160Thread B160Thread A160Thread AThread A170虽然大部分时候可以保证  但是有时候还是会出现A B交替运行的现象 这是为什么?
查看完整描述

目前暂无任何回答

  • 0 回答
  • 0 关注
  • 1209 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信