1.消费者和生产者的含义:
生产者生产产品,消费者去消费生产者生产的产品,就相当于是在读写过程一样,当生产者在生产产品时,当生产品在生产时,消费者就需要等待(wait),而生产者生产完之后就会唤醒消费者(notify)让消费者去消费,:而在消费者消费过程中,生产者在等待(wait),消费者消费完后就会唤醒生产者去生产(notify);而消费者和生产者相当于是两个线程,而产品就是他们的公共资源(cpu)当开启线程时要让两个交替循环的使用资源就必须要让他们同步使用(synchronized)
2.实例: package ShareDateDome;
//消费者
public class Consumer extends Thread {
private ShareDate s;
public Consumer(ShareDate s) {
this.s = s;
}
public void run(){
char ch ;
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ch=s.getShare();
} while (ch!='D');
}
}
package ShareDateDome;
import org.jboss.weld.exceptions.ForbiddenArgumentException;
//生产者
public class Producer extends Thread {
private ShareDate s;
public Producer(ShareDate s) {
this.s = s;
}
public void run(){
for (char ch='A'; ch <='D' ; ch++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s.putShare(ch);
}
}
}
package ShareDateDome;
/**
* 生产者和消费者***特别的难点
* 1.共享一个资源类2.生产者类3.消费者类
* @author lenovo
*
*/
public class ShareDate {
private char c;
private boolean isAdd=false;//true,有产品 false,无产品
//同步方法putShare();
public synchronized void putShare(char c){
//如果产品还未消费,则生产者等待
if (isAdd) {
//System.out.println("产品还未消费,因此生产者停止生产");
try {
wait(); //生产者等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.c=c;
isAdd=true; //表示有产品
notify(); //消费者消费,通知生产者生产
System.out.println("生产了产品"+c+"通知消费者消费");
}
//同步方法getShare();
public synchronized char getShare(){
//如果产品还未生产,则消费者等待
if (!isAdd) {
// System.out.println("产品还未生产,因此消费者停止消费");
try {
wait(); //消费者等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isAdd=false; //表示无产品
notify(); //生产者已经生产,通知消费者消费
System.out.println("消费者已经消费"+c+"通知生产者生产");
return c;
}
}
package ShareDateDome;
public class Test {
public static void main(String[] args) {
ShareDate sd=new ShareDate();
new Producer(sd).start();
new Consumer(sd).start();
}
}