您的位置:首页 > 编程语言 > Java开发

java多线程经典的生产者消费者问题

2016-08-09 09:58 579 查看
import java.io.*;
import java.lang.*;
import java.util.*;
public class hehe {
public static void main(String[] args){
Stack1 s= new Stack1();
Pruducer p= new Pruducer(s);
Consumer c = new Consumer(s);
new Thread(p).start();
new Thread(c).start();
}
}

public class Stack1 {
Wutou[] arr = new Wutou[6];
int index = 0;
public synchronized void push  (Wutou wt){
while(index == arr.length){//不用if的原因是可能异常会打断
try{
this.wait();//当前的对象访问的线程wait
}catch(InterruptedException e){
e.printStackTrace(); ;
}
}
this.notifyAll();
arr[index++] = wt;
}

public synchronized Wutou pop(){
while(index == 0){
try{
this.wait();//当前的对象访问的线程wait
}catch(InterruptedException ee){
ee.printStackTrace();
}
}
this.notifyAll();//叫醒一个线程继续执行
return arr[--index];
}

}

public class Wutou{
int id;
public Wutou(int id1){
id = id1;
}
public String toString(){
return "Wutou:"+ id;
}
}

public class Pruducer implements Runnable {
Stack1 ss = null;
Pruducer (Stack1 ss){
this.ss = ss;
}
public void run(){
for(int i = 0;i < 20;++ i){
Wutou w = new Wutou(i);
ss.push(w);
System.out.println("生产了:"+w);
try {
Thread.sleep(2000);
}catch(InterruptedException e){
return ;
}
}
}
}

public class Consumer implements Runnable{
Stack1 ss =null;
Consumer(Stack1 ss){
this.ss =ss ;
}
public void run(){
for(int i = 0;i < 20;++ i ){
Wutou w = new Wutou(i);
ss.pop();
System.out.println("消费了:"+w);
try {
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息