国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

線程的生產(chǎn)者和消費(fèi)者管程法的代碼

2020-04-15 10:27 作者:小垃圾kiki  | 我要投稿
package cn.jd.cooperation;

/*
?* 使用管程法實(shí)現(xiàn)生產(chǎn)者消費(fèi)者模式
?*/
public class CoTest01 {
?? ?public static void main(String[] args) {
?? ??? ?SynContainer container=new SynContainer();
?? ??? ?new Productor(container).start();
?? ??? ?new Consumer(container).start();
?? ?}
}

//多線程的生產(chǎn)者
class Productor extends Thread {
?? ?SynContainer container;

?? ?public Productor(SynContainer container) {
?? ??? ?this.container = container;
?? ?}

?? ?@Override
?? ?public void run() {
?? ??? ?// 生產(chǎn)
?? ??? ?for (int i = 1; i < 100; i++) {
?? ??? ??? ?System.out.println("生產(chǎn)第 -->"+i+"個饅頭");
?? ??? ??? ?container.push(new Steamedbun(i)); //new了饅頭的對象
?? ??? ?}
?? ?}
}

//多線程的消費(fèi)者
class Consumer extends Thread {
?? ?SynContainer container;

?? ?public Consumer(SynContainer container) {
?? ??? ?this.container = container;
?? ?}

?? ?@Override
?? ?public void run() {
?? ??? ?// 消費(fèi)
?? ??? ?for (int i = 0; i < 1000; i++) {
?? ??? ??? ?System.out.println("消費(fèi)第-->"+container.pop().id+"個饅頭");
?? ??? ??? ?
?? ??? ?}
?? ?}
}

//緩沖區(qū)
class SynContainer {
?? ?// 存儲數(shù)據(jù)的容器
?? ?Steamedbun[] buns = new Steamedbun[10];
?? ?int count = 0;// 計數(shù)器
?? ?// 儲存-->生產(chǎn)者做的事情

?? ?public synchronized void push(Steamedbun bun) {
?? ??? ?//何時能生產(chǎn)? 容器存在空間
?? ??? ?//不能生產(chǎn)? 只有等待
?? ??? ?if(count==buns.length) {
?? ??? ??? ?try {
?? ??? ??? ??? ?this.wait();??? //線程阻塞,消費(fèi)者通知生產(chǎn)解除
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//存在空間可以生產(chǎn)
?? ??? ?buns[count] = bun;
?? ??? ?count++;
?? ??? ?//存在數(shù)據(jù)了,可以通知消費(fèi)了
?? ??? ?this.notifyAll();
?? ?}

?? ?// 獲取-->消費(fèi)者做的事情
?? ?public synchronized Steamedbun pop() {
?? ??? ?//何時消費(fèi)??? 看容器中是否存在數(shù)據(jù)
?? ??? ?//沒有數(shù)據(jù)只有等待
?? ??? ?if(count==0) {
?? ??? ??? ?try {
?? ??? ??? ??? ?this.wait();//線程阻塞?? 生產(chǎn)者通知消費(fèi)解除阻塞
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//存在數(shù)據(jù)可以消費(fèi)
?? ??? ?count--;
?? ??? ?Steamedbun bun = buns[count];
?? ??? ?this.notifyAll();//消費(fèi)了有空間了就可以通知你生產(chǎn)了
?? ??? ?return bun;
?? ?}

}

//饅頭
class Steamedbun {
?? ??? ?int id;

?? ??? ?public Steamedbun(int id) {
?? ??? ??? ?this.id = id;
?? ??? ?}
?? ??? ?
}

線程的生產(chǎn)者和消費(fèi)者管程法的代碼的評論 (共 條)

分享到微博請遵守國家法律
平遥县| 齐河县| 大兴区| 永寿县| 翁牛特旗| 揭西县| 临泉县| 长寿区| 康平县| 临潭县| 招远市| 友谊县| 濉溪县| 荥阳市| 邯郸县| 西藏| 吴桥县| 五莲县| 凭祥市| 纳雍县| 施秉县| 宁安市| 阜南县| 白城市| 丰顺县| 田东县| 且末县| 黄平县| 丰台区| 松江区| 莆田市| 屯留县| 镇平县| 津市市| 龙岩市| 贵州省| 泸水县| 广东省| 大庆市| 灵璧县| 陆河县|