未分类
2020-08-30 12:54:48
1822677238@qq.com
手机扫码查看
匿名内部类完成生产者和消费者
public class demos{
public static void main(String[] args) {
MyStack ms=new MyStack();
Thread t1=new Thread(){
public void run() {
for(char c='A';c<='Z';c++){
ms.push(c+"");
}
}
};
Thread t2=new Thread(){
public void run() {
for(int i=0;i<26;i++){
ms.poll();
}
}
};
t1.start();
t2.start();
}
}
class MyStack{
private String[] values={"","","","",""};
private int size=0;
public synchronized void push(String s){
this.notifyAll();
while(values.length==size){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s+"入栈");
values[size]=s;
size++;
}
public synchronized void poll(){
this.notifyAll();
while(size==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(values[size-1]+"出栈");
values[size-1]="";
size--;
}
}
- 本页地址 https://www.9713job.com/?p=2216
- 上一篇 <<2020java教程:高级多线程
- 下一篇 >>2020java教程:Queue队列(接口)



发表回复