由于我是Java Threads的新手,我只是在试验我的代码。来自凯西' Sierra SCJP的书,我了解了thread.join()
方法。然后我学会了Synchronization
。以下是我使用thread.join()
方法而不是将makeWithdrawal()
方法设为synchronized
的代码。
AccountDanger 类:
public class AccountDanger implements Runnable{
private Account acct=new Account();
public static void main(String args[])throws InterruptedException{
AccountDanger r=new AccountDanger();
Thread one=new Thread(r);
Thread two=new Thread(r);// unable to start
one.setName("Fred");
two.setName("Lucy");
one.start();
one.join();// used join() instead of using synchronize keyword.
two.start();// unable to start
}
public void run(){
for(int x=0;x<5;x++){
makeWithdrawal(10);
if(acct.getBalance()<0){
System.out.println("Account is over-drawn");
}
}
}
private void makeWithdrawal(int amt){
if(acct.getBalance()>=amt){
System.out.println(Thread.currentThread().getName()+" is goint to withdraw");
try{
Thread.sleep(500);
}
catch(InterruptedException ex){}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()+" completes the withdrawal");
}
else{
System.out.println("Not enough in account for "+Thread.currentThread().getName()+" to withdraw "+acct.getBalance());
}
}
}
帐户类:
class Account{
private int balance=50;
public int getBalance(){
return balance;
}
public void withdraw(int amount){
balance=balance-amount;
}
}
但在看到输出(超过10次)后,我意识到我无法启动第二个线程(名为Lucy
的线程)。实际上,在使用two.isAlive()
print语句进行测试后,我发现它还活着。但为什么我看不到这个Lucy
线程有效呢?这是为什么?谁能帮我?以下是我得到的输出:
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
答案 0 :(得分:0)
一切都不对,但是:
等待Thread1的终止(加入等待,直到完成)。
将启动Thread2,但它是一个守护程序线程。如果主线程被终止,那么线程将被终止。
将您的代码更改为:
thread1.start();
thread2.start();
thread1.join();
thread2.join();
现在两个线程都将完成(并行工作)。
修改强>:
澄清:
one.start(); // Starts the execution of the runnable in Thread "one"
one.join(); // Waits for the Runnable to FINISH
two.start(); // after Thread "one" died, Thread "two" starts (no more moneys in the account)
加入(): Waits for this thread to die.
这与调用所有同步一样。