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();
}
}
}
}
java多线程经典的生产者消费者问题
最新推荐文章于 2024-02-10 12:15:21 发布