问题描述
- 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好像不起作用
解决方案
问题应该是出在这一句:synchronized(this)
搞个synchronized方法,run的时候调用它