java synchronized boolean_java中synchronized关键字
代碼示例:
package com.test;
/*
* x,y值為什么不能保持相同;
*
*/
public class Pair implements Runnable{
boolean b = false;
private int x;
private int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public Pair(){
}
public void incrementX(){
x++;
}
public void incrementY(){
y++;
}
public String toString(){
return "x: " + x + " ,y: "+y;
}
public void run(){
while(!b){
synchronized(this){
incrementX();
incrementY();
}
}
}
public boolean checkState(){
if(x!=y){
System.out.println("values not equal:"+this);
return b = true;
}
return b;
}
public static void main(String args[]){
Pair p = new Pair(0,0);
new Thread(p).start();
while(true){
System.out.println(p);
if(p.checkState()){
System.exit(0);
}
}
}
}
為什么以上代碼是線程不安全的?
在百科里面有這么一句:當(dāng)一個線程訪問object的一個synchronized(this)同步代碼塊時,另一個線程仍然可以訪問該object中的除synchronized(this)同步代碼塊以外的部分。
分析:請注意,在主線程中,會在某一個時刻調(diào)用p.checkState(),而這個方法并沒有和run方法中的
synchronized塊代碼同步。因為checkState方法不是同步方法。某一個時刻,synchronized塊失去了cpu。
而下一個卻要執(zhí)行主線程的p.checkState(),這個時候是可以訪問x 和 y變量的。
解決的方法是,需要同步的方法上,加一個synchronized。這樣就能和run方法中的synchronized塊進(jìn)行同步。
總結(jié)
以上是生活随笔為你收集整理的java synchronized boolean_java中synchronized关键字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Anaconda下载安装与手动配置环境变
- 下一篇: 编写网游客户端