Java多线程实现自然同步(内含演示案例)
1.准备一个生产者类:
public class Producer extends Thread{ private String name; private Market mkt; static int count; public Producer(String name, Market mkt) { super(name); this.mkt = mkt; } @Override public void run() { this.name = Thread.currentThread().getName(); System.out.println(name+"开始生产了!"); for (int i = 0; i < 5; i++) { try { Thread.sleep((long)(2000*Math.random())); } catch (InterruptedException e) { e.printStackTrace(); } count ++; String goods = "商品"+count; mkt.set(goods); } System.out.println(name+"生产完成!"); } }
2.准备一个消费者类:
public class Consumer extends Thread{ private String name; private Market mkt; public Consumer(String name,Market mkt){ super(name); this.mkt = mkt; } @Override public void run() { this.name = Thread.currentThread().getName(); System.out.println(name+"开始消费了!"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { try { Thread.sleep((long)(2000*Math.random())); } catch (InterruptedException e) { e.printStackTrace(); } String shoppingCart = mkt.get(); sb.append(shoppingCart).append(" | "); } System.out.println(name+"消费者购物完毕,所购清单如下:"); System.out.println("\t"+sb); } }
3.准备一个商场类:
public class Market { private String shelf; private boolean flag; public synchronized void set(String goods){ String name = Thread.currentThread().getName(); while(flag){ try { System.out.println(name+"试图上货但货架已满,请等待消费!"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.shelf = goods; this.flag = true; System.out.println(name+"已将"+goods+"上货,可以消费了!"); this.notify(); } public synchronized String get(){ String name = Thread.currentThread().getName(); while(!flag){ System.out.println(name+"试图购物,但货架已空,请等待上货!"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } String shoppingCart = shelf; this.shelf = null; this.flag = false; System.out.println(name+"购买了一个"+shoppingCart+"!"); this.notify(); return shoppingCart; } }
4.测试类:
public class Start { public static void main(String[] args) { Market mkt = new Market(); Producer p1 = new Producer("工人1", mkt); Producer p2 = new Producer("工人2", mkt); Consumer c = new Consumer("顾客", mkt); p2.start(); c.start(); p1.start(); } }