生产者与消费者
package ProConDemo;
//創(chuàng)建資源
public class Goods {
private String name;
//計(jì)數(shù)器
private int count = 1;
//創(chuàng)建一個(gè)標(biāo)記
private boolean flag;
//創(chuàng)建資源的生產(chǎn)行為
public synchronized void Sale(String name) {
//判斷標(biāo)記
while(flag)
//有資源就等待
try {wait();} catch (InterruptedException e) {e.printStackTrace();}
//沒有資源就生產(chǎn)
this.name = name +"----"+count;
count++;
System.out.println(Thread.currentThread().getName()+"生產(chǎn)了"+this.name);
//生產(chǎn)完畢改標(biāo)記
flag = true;
//喚醒所有等待線程
notifyAll();
}
//創(chuàng)建資源的消費(fèi)行為
public synchronized void Buy() {
//判斷標(biāo)記
while(!flag)
//沒有資源就等待
try {wait();} catch (InterruptedException e) {e.printStackTrace();}
//有資源就消費(fèi)
System.out.println(Thread.currentThread().getName()+"消費(fèi)了"+this.name);
//消費(fèi)完畢改標(biāo)記
flag = false;
//喚醒所有等待線程
notifyAll();
}
}
?
package ProConDemo;
//創(chuàng)建消費(fèi)者任務(wù)類
public class Cou implements Runnable{
private Goods good;
//將資源對(duì)象作為參數(shù)傳入消費(fèi)者的構(gòu)造函數(shù)中
public Cou(Goods good) {
this.good = good;
}
//覆蓋run()
public void run() {
while(true)
good.Buy();
}
}
package ProConDemo;
//創(chuàng)建生產(chǎn)者任務(wù)類
public class Pro implements Runnable{
private Goods good;
//將資源對(duì)象作為參數(shù)傳入生產(chǎn)者構(gòu)造函數(shù)中
public Pro(Goods good) {
this.good = good;
}
//覆蓋run()
public void run() {
while(true)
good.Sale("面包");
}
}
//執(zhí)行
package ProConDemo;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//創(chuàng)建資源對(duì)象
Goods good = new Goods();
//創(chuàng)建生產(chǎn)與消費(fèi)任務(wù)對(duì)象
Pro pro = new Pro(good);
Cou cou = new Cou(good);
//創(chuàng)建線程,并將任務(wù)對(duì)象傳入
Thread t0 = new Thread(pro);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(cou);
Thread t3 = new Thread(cou);
//啟動(dòng)線程
t0.start();
t1.start();
t2.start();
t3.start();
}
}
轉(zhuǎn)載于:https://www.cnblogs.com/olddriver123/p/8250863.html
總結(jié)
- 上一篇: android 万能倒计时,时分秒倒计时
- 下一篇: java实现modbus rtu协议与