java同步--synchronized小例子

 

void dosth(){
for(int i=0;i<5000;i++){
new addman().start();
new getman().start();
}
}

private static int b = 0;

String lock = "a";
void add(){
synchronized(lock){
b = b + 10;
}
System.out.println("add+10, b = " + b);
}

synchronized void get(){
synchronized(lock){
b = b - 10;
}
System.out.println("get-10, b = " + b);
}



class addman extends Thread{

@Override
public void run() {

//System.out.println("当前线程="+Thread.currentThread());
add();
}

}

class getman extends Thread{

@Override
public void run() {

//System.out.println("当前线程="+Thread.currentThread());
get();
}

}

posted @ 2016-07-17 21:55  蔡昊  阅读(207)  评论(0编辑  收藏  举报