我有2节课,
public class Account {
private int balance = 50;
public int getBalance() {
return balance;
}
public void withdraw(int amt){
this.balance -= amt; } }
和
public class DangerousAccount implements Runnable{
private Account acct = new Account();
public static void main(String[] args) throws InterruptedException{
DangerousAccount target = new DangerousAccount();
Thread t1 = new Thread(target);
Thread t2 = new Thread(target);
t1.setName("Ravi");
t2.setName("Prakash");
t1.start();
/* #1 t1.join(); */
t2.start();
}
public void run(){
for(int i=0; i<5; i++){
makeWithdrawl(10);
if(acct.getBalance() < 0)
System.out.println("Account Overdrawn");
}
}
public void makeWithdrawl(int amt){
if(acct.getBalance() >= amt){
System.out.println(Thread.currentThread().getName() + " is going to withdraw");
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName() + " has finished the withdrawl");
}else{
System.out.println("Not Enough Money For " + Thread.currentThread().getName() + " to withdraw");
}
}
}
我尝试在 makeWithdrawl 方法中添加同步关键字
public synchronized void makeWithdrawl(int amt){
我尝试多次得到这个输出
Ravi is going to withdraw
Ravi has finished the withdrawl
Ravi is going to withdraw
Ravi has finished the withdrawl
Ravi is going to withdraw
Ravi has finished the withdrawl
Ravi is going to withdraw
Ravi has finished the withdrawl
Ravi is going to withdraw
Ravi has finished the withdrawl
Not Enough Money For Prakash to withdraw
Not Enough Money For Prakash to withdraw
Not Enough Money For Prakash to withdraw
Not Enough Money For Prakash to withdraw
Not Enough Money For Prakash to withdraw
这表明只有线程 t1 正在工作......
如果我取消注释这行说
t1.join();
并从 makeWithdrawl 方法中删除同步关键字,我得到相同的输出。
如果我不使用 synchronize 关键字或 join() 我会得到各种输出,例如
Ravi is going to withdraw
Prakash is going to withdraw
Prakash has finished the withdrawl
Ravi has finished the withdrawl
Prakash is going to withdraw
Ravi is going to withdraw
Prakash has finished the withdrawl
Ravi has finished the withdrawl
Prakash is going to withdraw
Ravi is going to withdraw
Prakash has finished the withdrawl
Ravi has finished the withdrawl
Account Overdrawn
Account Overdrawn
Not Enough Money For Ravi to withdraw
Account Overdrawn
Not Enough Money For Prakash to withdraw
Account Overdrawn
Not Enough Money For Ravi to withdraw
Account Overdrawn
Not Enough Money For Prakash to withdraw
Account Overdrawn
那么 synchronized 的输出与 join() 有何不同?我们是否需要将 synchronized 关键字添加到 run() ?