标签:否则 rup not tty ati ace interrupt trace 定义
public class TestProduct {public static void main(String[] args) {Clerk clerk = new Clerk();Consumer con = new Consumer(clerk);Producer pro = new Producer(clerk);Thread t1 = new Thread(con);Thread t2 = new Thread(con);Thread t3 = new Thread(pro);Thread t4 = new Thread(pro);t1.setName("1");t2.setName("2");t3.setName("1");t4.setName("2");t1.start();t2.start();t3.start();t4.start();}}class Clerk {int numOfProduction;// 共享資源public synchronized void produce() {// 定义生产共享资源的方法if (numOfProduction == 20) {// 达到20个则暂停生产,否则继续生产并且唤醒消费try {wait();} catch (InterruptedException e) {e.printStackTrace();}} else {try {Thread.currentThread().sleep(100);} catch (InterruptedException e) {e.printStackTrace();}numOfProduction++;System.out.println(Thread.currentThread().getName() + "号生产者生产了货架上第" + numOfProduction + "号产品");notifyAll();}}public synchronized void consume() {// 定义消费共享资源的方法if (numOfProduction == 0) {// 达到0个则暂停消费,否则继续消费并且唤醒生产try {wait();} catch (InterruptedException e) {e.printStackTrace();}} else {try {Thread.currentThread().sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "号消费者消费了货架上第" + numOfProduction + "号产品");numOfProduction--;notifyAll();// 已消费,唤醒生产者生产}}}class Producer implements Runnable {Clerk clerk;public Producer(Clerk clerk) {super();this.clerk = clerk;}@Overridepublic void run() {while (true) {clerk.produce();}}}class Consumer implements Runnable {Clerk clerk;public Consumer(Clerk clerk) {super();this.clerk = clerk;}@Overridepublic void run() {while (true) {clerk.consume();}}}
标签:否则 rup not tty ati ace interrupt trace 定义
原文地址:http://www.cnblogs.com/chendifan/p/6551164.html