wait\notify

管程法
package Thread.Demo10;
public class ProductorModem {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
class Productor extends Thread {
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chickden(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 Chickden {
int id;
public Chickden(int id) {
this.id = id;
}
}
class SynContainer {
Chickden[] chickdens = new Chickden[10];
int count = 0;
public synchronized void push(Chickden chickden) {
if (count == chickdens.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chickdens[count] = chickden;
count++;
this.notifyAll();
}
public synchronized Chickden pop() {
if (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Chickden chickden = chickdens[count];
this.notifyAll();
return chickden;
}
}
信号灯法
package Thread.Demo10;
public class xinhaodengfa {
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++) {
tv.watch();
}
}
}
class TV {
String voice;
boolean flag = true;
public synchronized void play(String voice) {
if (!flag) {
this.voice = voice;
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演:" + voice);
this.notifyAll();
this.flag = !this.flag;
}
public synchronized void watch() {
if (flag) {
this.voice = voice;
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众看:" + voice);
this.notifyAll();
this.flag = !this.flag;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现