在java中哪些类生产消费者模型
答案:1 悬赏:40 手机版
解决时间 2021-02-13 06:24
- 提问者网友:世勋超人
- 2021-02-12 14:30
在java中哪些类生产消费者模型
最佳答案
- 五星知识达人网友:归鹤鸣
- 2021-02-12 15:09
public class Consumer extends Thread {
private ShareData shareData;
public Consumer(ShareData shareData){
this.shareData = shareData;
}
@Override
public void run() {
do {
char c = shareData.getChar();
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(c == 'Z'){
break;
}
} while (true);
}
}
public class Producer extends Thread {
private ShareData shareData;
public Producer(ShareData shareData){
this.shareData = shareData;
}
@Override
public void run() {
for(char c = 'A'; c <= 'Z'; c++){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shareData.putChar(c);//生产
}
}
}
public class ShareData {
char ch;//资源
boolean isproduce = false;//表示没有资源
String str = "消费";
//生产方法
public synchronized void putChar(char c){
if(isproduce){
System.out.println("仓库中 有 东西");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.ch = c;
isproduce = true;//表示仓库中有东西
System.out.println("仓库中生产了 " + ch);
notify();
}
//消费的方法
public synchronized char getChar(){
if(!isproduce){
System.out.println("仓库中 没有 东西 ");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (str) {
if(!isproduce){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isproduce = false;
System.out.println(Thread.currentThread().getName() + " 消费了:" + ch);
notify();//通知生产
return ch;
}
}
}
public class Test {
public static void main(String[] args) {
ShareData shareData = new ShareData();
Producer producer = new Producer(shareData);
Consumer consumer = new Consumer(shareData);
consumer.setName("x");
Consumer consumer2 = new Consumer(shareData);
consumer2.setName("y");
consumer.start();
consumer2.start();
producer.start();
}
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯