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();
}
}
}
该博客主要使用Java语言实现基本的生产者、消费者多线程模式。定义了产品接口、产品类,以及生产者和消费者线程类。在实现过程中,增加了同步机制,并对同步进行了优化,通过wait()和notify()方法协调生产者和消费者的操作。
557

被折叠的 条评论
为什么被折叠?



