1.生产者消费者问题是实现线程同步的经典案例。
这里做一个对生产消费者问题做一个模拟:
我这里用一个 stack栈 用来存放产品,生产者生产产品,消费者消费产品,
class Stacks
{
int index=0;
matou []ms=new matou[6];
public synchronized void push(matou m){
if(index==ms.length){
try{
this.wait();
}catch (Exception e){}
}
ms[index++]=m;
this.notify();
}
产品:
class matou
{
private int id;
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
public matou(int id){
this.id=id;
}
}
生产者和消费者对栈的操作(开启器线程)
class Pro implements Runnable{
private Stacks s;
public Pro (Stacks s){
this.s=s;
}
public void run(){
for(int i=0;i<20;i++){
matou m=new matou(i+1);
s.push(m);
System.out.print("生产了一个码头: matou"+m.getId());
try{ Thread.sleep(1000);}catch (Exception e){}
System.out.println();
}
}
}
class Cus implements Runnable{
private Stacks s;
public Cus (Stacks s){
this.s=s;
}
public void run(){
for(int i=0;i<20;i++){
matou m=s.pop();
try{ Thread.sleep(2000);}catch (Exception e){}
System.out.println();
System.out.println("消费了一个码头:matou"+m.getId());
System.out.println();
}
}
}
public class Pro_Cus{
public static void main(String args[]){
Stacks s=new Stacks();
new Thread(new Cus(s)).start();
new Thread(new Pro(s)).start();
}
}
这里用到的synchornized关键字,用到了wait和signal机制,一个简单的模拟;
运行截图:设置的循环二十次,只是部分截图。