我不能使用同步正確:Java同步-IllegalMonitorStateException
在以下我有2個問題的代碼:
1.而makingmethods(designBusiness,createBusiness,sellBusiness)作爲像在這種情況下,一個呼叫wait()
說IllegalMonitorStateException
但我不明白爲什麼?因爲在designBusiness
方法Designer Thread
確實得到一個鎖,所以它應該等待wait
呼叫。我在wait()
和notify()
上都收到IllegalMonitorStateException。
2.Even雖然當我刪除關鍵字,並使用synchronized(this)
塊特別wait()
和notify()
還是我得到了死鎖!爲什麼?
public class Main {
HashMap<String, Integer> map = new shop().orderBook();
public static void main(String[] args) throws InterruptedException {
Main main = new Main();
main.sellBusiness();
Thread.sleep(3000);
main.designBusiness();
Thread.sleep(3000);
main.createBusiness();
}
private synchronized void designBusiness() throws InterruptedException {
Thread designThread = new Thread(new Runnable() {
public void run() {
Set set = map.keySet();
System.out.println("Tracking OrderList");
System.out.println(set.size());
try {
System.out.println("waiting.........");
wait();
System.out.println("wait completed");
System.out.println("after design process items in orderList are "
+ map.keySet().size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Designer Thread");
designThread.start();
System.out
.println("status of Designer Thread" + designThread.isAlive());
}
private synchronized void createBusiness() throws InterruptedException {
Thread createThread = new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()
+ " started");
Creator creator = new Creator();
creator.create(map);
notifyAll();
System.out.println("notified");
}
}, "Creator Thread");
createThread.start();
createThread.join();
System.out.println("status of Creator Thread" + createThread.isAlive());
}
private void sellBusiness() throws InterruptedException {
Thread sellThread = new Thread(new Runnable() {
public void run() {
Seller seller = new Seller();
seller.sellGold(45000, 15);
seller.sellSilver(14000, 60);
seller.noteOrder("Mrs Johnson", 15000, map);
seller.noteOrder("Mr. Sharma", 10000, map);
seller.sellGold(60000, 20);
seller.noteOrder("Mr. Hooda", 17500, map);
System.out.println(Thread.currentThread().getName()
+ " done selling");
}
}, "Seller Thread");
sellThread.start();
sellThread.join();
System.out.println("status of seller Thread" + sellThread.isAlive());
}
}
請幫助我找不到任何解決方案,這個問題,我從昨晚搜索。
DEADLOCK?哪些線程被鎖定?主要和設計師和創造者? – johnchen902
@ johnchen902由於設計師和創作者的原因造成的死鎖。我不認爲是原因。 –