1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
class Clerk{
private int productCount = 0; public synchronized void produceProduct() {
if(productCount < 20){ productCount++; System.out.println(Thread.currentThread().getName() + ":开始生产第" + productCount + "个产品");
notify();
}else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
} public synchronized void consumeProduct() { if(productCount > 0){ System.out.println(Thread.currentThread().getName() + ":开始消费第" + productCount + "个产品"); productCount--;
notify(); }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
} }
class Producer extends Thread{
private Clerk clerk;
public Producer(Clerk clerk) { this.clerk = clerk; }
@Override public void run() { System.out.println(getName() + ":开始生产产品.....");
while(true){
try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
clerk.produceProduct(); }
} }
class Consumer extends Thread{ private Clerk clerk;
public Consumer(Clerk clerk) { this.clerk = clerk; }
@Override public void run() { System.out.println(getName() + ":开始消费产品.....");
while(true){
try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
clerk.consumeProduct(); } } }
public class ProductTest {
public static void main(String[] args) { Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk); p1.setName("生产者1");
Consumer c1 = new Consumer(clerk); c1.setName("消费者1"); Consumer c2 = new Consumer(clerk); c2.setName("消费者2");
p1.start(); c1.start(); c2.start();
} }
|