我正在嘗試wait()
和notify()
用於多線程的方法。在多線程中使用wait()和notify()
我想出了一個小型項目,我試圖用多線程解決。 我有一輛出租車,將達到6級,我有一個乘客,將達到Rank6。
出租車將到達排名第6的乘客,並將爲wait()
乘客。 當乘客到達Rank6時,他會notify()
。
在得到通知後,該出租車將繼續循環,並且不會向其他等級。
Taxi.java
package multhithreading.engage.hireForHier;
public class Taxi implements Runnable {
Rank rank = null;
public Taxi(Rank rank) {
this.rank = rank;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " Destined for rank No. " + rank.getRankNo());
synchronized (rank) {
for (int i = 1; i < 10; i++) {
System.out.println("Taxi has reached rank: " + i);
if (i == 6) {
try {
rank.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}// catch
}// if
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}// catch
}// for
}// synchronized
}// run
}
Passenger.java
package multhithreading.engage.hireForHier;
public class Passenger implements Runnable {
Rank rank = null;
public Passenger(Rank rank) {
this.rank = rank;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " Destined for rank No. " + rank.getRankNo());
synchronized (rank) {
for (int i = 1; i < 10; i++) {
System.out.println("Passenger has reached rank: " + i);
if (i == 6) {
notify();
}// if
try {
Thread.sleep(180);
} catch (InterruptedException e) {
e.printStackTrace();
}// catch
}// for
}// synchronized
}// run
}
Rank.java
package multhithreading.engage.hireForHier;
public class Rank {
private int rankNo = 0;
public Rank(int rankNo) {
this.rankNo = rankNo;
}
public int getRankNo() {
return rankNo;
}
}
TaxiHire.java
package multhithreading.engage.hireForHier;
public class TaxiHire {
public static void main(String[] args) {
Rank rank6 = new Rank(6);
Taxi taxiNo3 = new Taxi(rank6);
Passenger passengerNo3 = new Passenger(rank6);
Thread taxi_thread = new Thread(taxiNo3, "taxi_thread");
Thread passenger_thread = new Thread(passengerNo3, "passenger_thread");
taxi_thread.start();
passenger_thread.start();
}
}
我得到的輸出是:
taxi_thread Destined for rank No. 6
Taxi has reached rank: 1
passenger_thread Destined for rank No. 6
Taxi has reached rank: 2
Taxi has reached rank: 3
Taxi has reached rank: 4
Taxi has reached rank: 5
Taxi has reached rank: 6
Passenger has reached rank: 1
Passenger has reached rank: 2
Passenger has reached rank: 3
Passenger has reached rank: 4
Passenger has reached rank: 5
Passenger has reached rank: 6
Exception in thread "passenger_thread" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at lesson9.engage.hireForHier.Passenger.run(Passenger.java:20)
at java.lang.Thread.run(Unknown Source)
我需要知道爲什麼異常被拋出越來越對我來說,它看起來像出租車線程沒有找回鎖。 這個場景應該如何實現以及Taxi線程如何繼續循環。
您的幫助將真正被讚賞。
感謝user2511414,這是非常有幫助的。 – user2106149
我很高興我可以給一些手:)有一個很好的並行應用程序。 – 2013-10-17 20:45:51