1、利用緩沖區解決:管程法
// 生產者、消費者、產品、緩沖區
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Production(container).start();
new Consumer(container).start();
}
}
// 生產者
class Production extends Thread {
SynContainer container;
public Production(SynContainer container) {
this.container = container;
}
// 生產
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生產了" + i + "只雞");
}
}
}
// 消費者
class Consumer extends Thread {
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
// 消費
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消費了---->>" + container.pop().id + "只雞");
}
}
}
// 產品
class Chicken {
int id; // 編號
public Chicken(int id) {
this.id = id;
}
}
// 快取區
class SynContainer {
// 需要一個容器大小
Chicken[] chickens = new Chicken[10];
// 容器計數器
int count = 0;
// 生產者放入產品
public synchronized void push(Chicken chicken) {
// 如果容器滿了,需要等待消費者消費
if (count == chickens.length) {
// 通知消費者消費,生產者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果沒有滿就丟入產品
chickens[count] = chicken;
count++;
//通知消費者消費
this.notifyAll();
}
// 消費者消費產品
public synchronized Chicken pop() {
// 判斷能否消費
if (count == 0) {
// 等待生產者生產,消費者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果可以消費
count--;
Chicken chicken = chickens[count];
// 通知生產者 吃完了
this.notifyAll();
return chicken;
}
}
2、利用標志位解決:信號燈法
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
// 生產者-->演員
class Player extends Thread{
TV tv;
public Player(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
this.tv.play("快樂大本營播放中..");
} else {
this.tv.play("抖音:記錄美好生活..");
}
}
}
}
// 消費者-->觀眾
class Watcher extends Thread {
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.tv.watch();
}
}
}
// 產品-->節目
class TV extends Thread {
// 演員表演,關眾等待 T
// 關眾觀看,演員等待 F
String video; // 節目
boolean flag = true; // 標記
// 表演
public synchronized void play(String video) {
if (!flag) {
// 演員等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演員表演了:" + video);
// 通知關眾觀看
this.notifyAll(); // 通知喚醒
this.video = video;
this.flag = !this.flag;
}
// 觀看
public synchronized void watch() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("觀看了:"+video);
// 通知演員表演
this.notifyAll();
this.flag = !this.flag;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252925.html
標籤:其他
上一篇:深度閱讀:C語言指標,從底層原理到花式技巧,圖文+代碼透析
下一篇:演算法分析——動態規劃
