【发布时间】:2020-08-17 14:18:00
【问题描述】:
整个程序是:
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class AccountWithConditionsUser {
private static Account account = new Account();
public static void main(String[] args) {
System.out.println("Thread 1\t\tThread 2\t\tBalance");
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new DepositTask());
executor.execute(new WithdrawTask());
executor.shutdown();
while(!executor.isShutdown()) {
}
}
public static class DepositTask implements Runnable{
public void run() {
try {
while(true) {
account.deposit((int)(Math.random()* 10)+ 1);
Thread.sleep(1000);
}
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
public static class WithdrawTask implements Runnable{
public void run() {
while(true) {
account.withdraw((int)(Math.random() * 10) + 1);
}
}
}
private static class Account{
private static Lock lock = new ReentrantLock(true);
private static Condition newDeposit = lock.newCondition();
private int balance = 0;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
lock.lock();
System.out.println("->Withdraw Obtained Lock");
try {
while(balance < amount) {
System.out.println("\t\t\tWait for deposit");
newDeposit.await();
}
balance-=amount;
System.out.println("\t\t\tWithdraw "+ amount + "\t\t" + getBalance());
}
catch(Exception e) {
e.printStackTrace();
}
finally {
System.out.println("->Withdraw Released Lock");
lock.unlock();
}
}
public void deposit(int amount) {
lock.lock();
System.out.println("->Deposit Obtained Lock");
try {
balance+=amount;
System.out.println("Deposit "+ amount + "\t\t\t\t\t" + getBalance());
newDeposit.signalAll();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
System.out.println("->Deposit Released Lock");
lock.unlock();
}
}
}
}
我得到的这段代码输出的示例部分是:
......
......
撤销已释放的锁
撤销获得的锁
等待存款
存款获得锁
存款 9 13
存款释放锁
退出 9 4
撤销已释放的锁
.....
.....
这里的问题是窗口获得锁后存款线程如何获得锁。不是说一旦获得了锁,其他线程就无法获得!还是因为信号方法?谁能解释一下这个输出是怎么来的? 在此先感谢:)
【问题讨论】:
标签: java multithreading