JAVA多線程-生產者與消費者當線程多時發生死結的解決方案

來源:互聯網
上載者:User

快要考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();
}
}
}
 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.