2 hk700wang hk700wang 于 2014.08.12 09:48 提问

java synchronized没有起作用

package com.wxb.syn;

class Semaphore{}

public class BalanceTest extends Thread{
public static int balance = 100;
public Semaphore semp = new Semaphore();
public void run() {
synchronized(this){
// System.out.println("balance=" + balance);
if(balance == 100) {
// try {
// sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
balance = balance - 100;
System.out.println(balance);
System.out.println("withdraw 100 successful!");
}else{
System.out.println("failed");
}
}

}
public static void main(String[] args) {
    BalanceTest bt = new BalanceTest();
    bt.start();
    BalanceTest bt2 = new BalanceTest();
    bt2.start();
    BalanceTest bt3 = new BalanceTest();
    bt3.start();
    BalanceTest bt4 = new BalanceTest();
    bt4.start();
    BalanceTest bt5 = new BalanceTest();
    bt5.start();
    BalanceTest bt6 = new BalanceTest();
    bt6.start();
}

}

不加sleep只有一个successful,加了之后都成功synchronized好像不起作用

1个回答

qwuack
qwuack   2014.08.12 10:52

问题应该是出在这一句:synchronized(this)
搞个synchronized方法,run的时候调用它

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!