思路:
和生产者消费者模型一样。
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(); } }
输出结果:
这个操作不用考虑同步等问题,直接使用等待与唤醒机制就行了,一进一出就搞定。