快要考JAVA了,研究了一下書上的生產者與消費者的執行個體,書上只是單個消費者與單個生產者的程式,我在它的基礎上,改成多個生產者多個消費者,不幸的事情發生了,居然給死結掉了,百思不得其解,研究了整個早上,後台通過和老師的討論終於找到了原因-------notify()是隨機喚醒一個線程
如果生產者生產好東西,然後一直隨機喚醒的線程都是生產者那就產生死結了,改用notifyAll()則可以避免死結,但是效率會降低,不過總比死結來的好得多。
程式碼:
common倉庫類
package threadlocktest;
/**
*
* @author DJ尐舞
*/
public class common {
private char ch;
private boolean available = false;
synchronized char get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return ch;
}
synchronized void put(char newch) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
ch=newch;
available = true;
notifyAll();
}
}
消費者:
package threadlocktest;
/**
*
* @author DJ尐舞
*/
public class consumer extends Thread{
private common comm;
public consumer(common thiscomm){
this.comm=thiscomm;
}
public void run(){
char c;
for(int i=0;i<5;i++){
c=comm.get();
System.out.println("消費者得到的資料是:"+c);
}
}
}
生產者:
package threadlocktest;
/**
*
* @author DJ尐舞
*/
public class producer extends Thread {
private common comm;
public producer(common thiscomm) {
comm = thiscomm;
}
public void run(){
char c;
for(c='a';c<='e';c++){
comm.put(c); System.out.println("生產者者的資料是:"+c);
}
}
}
main函數
Code
package threadlocktest;
/**
*
* @author DJ尐舞
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
common comm = new common();
for (int i = 0; i < 100; i++) {
new producer(comm).start();
new consumer(comm).start();
}
}
}