package Chenqi;
import java.io.InterruptedIOException;
/**
*1、制作出基本的生产者、消费者多线程模式
*2、在1的基础上,增加同步
*3、在2的基础上优化同步
*/
public class ThreadTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Productable p=new Product();
Producer put=new Producer(p);
Consumer get=new Consumer(p);
}
}
//定义产品接口
interface Productable{
void get();
void put(int productID);
boolean isHasProduct();
void reset();
}
//定义产品类
class Product implements Productable{
int productID=0;
private volatile boolean hasProduct=false;
public boolean isHasProduct() {
return this.hasProduct;
}
public void reset() {
this.productID=0;
}
synchronized public void get() {
if(!this.isHasProduct()){
try {
wait();
} catch (InterruptedException e) {
System.out.println("get process interrupted!");
}
}
System.out.println("get : "+this.productID);
this.hasProduct=false;
this.reset();
notify();
}
synchronized public void put(int productID) {
if(this.isHasProduct()){
try {
wait();
} catch (InterruptedException e) {
System.out.println("put process interrupted!");
}
}
this.productID=productID;
System.out.println("put : "+this.productID);
this.hasProduct=true;
notify();
}
}
//定义生产者线程
class Producer implements Runnable{
Productable p;
public Producer(Productable p) {
this.p=p;
new Thread(this,"Producer").start();
}
public void run() {
int i=2;
while(true){
p.put(++i);
}
}
}
//定义消费者类
class Consumer implements Runnable{
Productable p;
public Consumer(Productable p) {
this.p=p;
new Thread(this,"Consumer").start();
}
public void run() {
while(true){
p.get();
}
}
}