思路:
和生产者消费者模型一样。
public class Computer { private static int count = 0; // 生产的个数 private String name; // 电脑的名称 private double price; // 电脑的价格 public Computer(String name, double price){ this.name = name; this.price = price; count ++ ; } public String toString(){ return "第【" + count + "台电脑】" + " - 电脑名称:" + this.name + "\t电脑价格: " + this.price; } }
public class Resource { //操作类 private Computer computer; public synchronized void create(){ if (this.computer != null){ // 已经生产了电脑,等待取走 try { super.wait(); // 等待取走 } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("生产完毕!"); this.computer = new Computer("ASUS",1000); super.notifyAll(); } public synchronized void get(){ if (this.computer == null){ try { super.wait(); // 等待生产 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(this.computer); this.computer = null; // 已经取走电脑,没有电脑了 super.notifyAll(); } }
public class Producer implements Runnable{ // 生产电脑线程类 private Resource resource; public Producer(Resource resource){ this.resource = resource; } @Override public void run() { for (int i = 0; i < 10; i++) { this.resource.create(); } } }
public class Comsumer implements Runnable{ // 取走电脑线程类 private Resource resource; public Comsumer(Resource resource){ this.resource = resource; } @Override public void run() { for (int i = 0; i < 10; i++) { this.resource.get(); } } }
public class Main { public static void main(String[] args) { Resource resource = new Resource(); new Thread(new Producer(resource)).start(); new Thread(new Comsumer(resource)).start(); } }
输出结果:
这个操作不用考虑同步等问题,直接使用等待与唤醒机制就行了,一进一出就搞定。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)