最近在学习线程同步问题,接触了生产者和消费者问题:
生产者生产产品、消费者消费产品,两者同时进行,怎么样实现两者的线程同步?
1.此问题中首先要搞清楚问题中有哪两个线程(生产者和消费者)
2.线程同步有什么必要性(现实生活中的实例)
3.线程之间的关系(线程之间应该有个产品的缓冲区来形成两个线程之间的关系)
4.两个线程共享同一个缓冲区
5.缓冲区满,生产者等待。缓冲区空,消费者等待
public class ProducerConsumer {
public static void main(String[] args) {
Store s = new Store();
Producer p = new Producer(s);
Producer p1 = new Producer(s);
//Producer p2 = new Producer(s);
Consumer su = new Consumer(s);
//Consumer su1 = new Consumer(s);
//Consumer su2 = new Consumer(s);
new Thread(p).start();
new Thread(p1).start();
//new Thread(p2).start();
new Thread(su).start();
//new Thread(su1).start();
// Thread(su2).start();
}
}
class Product{//
int id;
Product(int id){
this.id = id;
}
public String toString(){
return "Product:"+id;
}
}
class Producer implements Runnable{//
Store s = null;
Producer(Store s){
this.s = s;
}
public void run(){
for(int i = 0;i<10;i++){
Product p = new Product(i);
s.put(p);
System.out.println("生产:"+p);
}
}
}
class Consumer implements Runnable{//
Store s = null;
Consumer(Store s){
this.s = s;
}
public void run(){
for(int i = 0;i<10;i++){
Product p = s.get();
System.out.println("消费:"+p);
}
}
}
class Store{//
static Product[] p = new Product[10];
static int index = 0;//
public synchronized void put(Product pro){//
if(index == p.length){
try{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.notifyAll();
p[index] = pro;
index++;
}
public synchronized Product get(){//
if(index == 0){
try{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.notifyAll();
index--;
return p[index];
}
}