我遇到了兩個線程似乎沒有正確同步的問題。我基本上有一個布爾值名稱「佔用」。當沒有線程啓動時,它被設置爲false。但是當一個開始,線程集佔用是真的我有一個類有線程(運行),他們調用下面的函數。多線程生產者/消費者同步問題
這是一個模擬銀行示例,它接收一定金額(初始餘額),然後隨機執行提款和存款。我的教授提到了一些有關從存款線索中提取信號的信號?這是如何運作的?退出線程,它應該運行,直到餘額爲兩個低,並等待存款線程。我應該怎麼做?
package bank;
import java.util.Random;
import bank.Bank;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;
/**
*
* @author KJ4CC
*/
public class Action {
private Lock accessLock = new ReentrantLock();
private Condition cond = accessLock.newCondition();
//private Condition withdraw = accessLock.newCondition();
Random rand = new Random();
Object lock = new Object();
Bank getBalance = new Bank();
public void widthdrawl(int threadNum) throws InterruptedException {
int amount = rand.nextInt(50);
accessLock.lock();
if (getBalance.getbalance() > amount) {
getBalance.setBalance(getBalance.getbalance() - amount);
System.out.println("\t\t\tThread " + threadNum + " withdrawls " + amount + "\t Balance is " + getBalance.getbalance());
} else {
System.out.println("\t\t\tThread " + threadNum + " Failed to withdrawl " + amount + "\t Balance is " + getBalance.getbalance());
cond.await();
}
accessLock.unlock();
Thread.sleep(rand.nextInt(5));
}
public void deposit(int threadNum) throws InterruptedException {
int amount = rand.nextInt(200);
accessLock.lock();
getBalance.setBalance(getBalance.getbalance() + amount);
System.out.println("Thread " + threadNum + " Deposits " + amount + "\t\t\t\t Balance is " + getBalance.getbalance());
Thread.sleep(rand.nextInt(100));
cond.signal();
accessLock.unlock();
}
}
嘗試結帳一個BlockingQueue。 –