快要考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();
}
}
}