亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的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 關注
  • 1239 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號