成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

java - 線程同步為什么不一樣

瀏覽:122日期:2024-01-03 09:45:27

問(wèn)題描述

package com.dome;

public class Thread01 {

private volatile static int a =10;Thread td1 = new Thread(){public void run(){for(int i=0;i<3;i++){ a = a+1;System.out.println(i+'td1:='+a);} } };Thread td2 = new Thread(){ public void run(){for(int i=0;i<3;i++){ a -=1; System.out.println(i+'td2:='+a);} } };public static void main(String[] args) { Thread01 th = new Thread01(); th.td1.start();th.td2.start(); }

}

0td1:=90td2:=91td1:=101td2:=92td1:=102td2:=9

問(wèn)題解答

回答1:

a = a + 1, a = a - 1 這樣的語(yǔ)句,事實(shí)上涉及了 讀?。薷模瓕?xiě)入 三個(gè)操作:

讀取變量到棧中某個(gè)位置

對(duì)棧中該位置的值進(jìn)行加 (減)1

將自增后的值寫(xiě)回到變量對(duì)應(yīng)的存儲(chǔ)位置

因此雖然變量 a 使用 volatile 修飾,但并不能使涉及上面三個(gè)操作的 a = a + 1,a = a - 1具有原子性。為了保證同步性,需要使用 synchronized:

public class Thread01 { private volatile static int a = 10; Thread td1 = new Thread() {public void run() { for (int i = 0; i < 3; i++) {synchronized (Thread01.class) { a = a + 1; System.out.println(i + 'td1:=' + a);} }} }; Thread td2 = new Thread() {public void run() { for (int i = 0; i < 3; i++) {synchronized (Thread01.class) { a -= 1; System.out.println(i + 'td2:=' + a);} }} }; public static void main(String[] args) {Thread01 th = new Thread01();th.td1.start();th.td2.start(); }}

某次運(yùn)行結(jié)果:java - 線程同步為什么不一樣

(td1 出現(xiàn)的地方,a 就 +1;td2 出現(xiàn)的地方,a 就 -1)

標(biāo)簽: java
相關(guān)文章: