java多线程之生产者消费者经典问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chekongfu/article/details/43237365
package com.thread;

/**
 * 	此程序不仅可以加深对多线程的理解,并且可以加深对面向对象编程的理解
 *  此程序并非是一个很完善的程序,阅读代码的过程中要发现发生死锁的原因以及找到解决问题的方法
 *  
 * 	cehkongfu:2015.1.28
 */

class Factory {
	private int i = 0;
	private boolean created = false;
	
	public void create() {
		synchronized (this) {
			if (created) {
				try {
					wait();
				} catch (InterruptedException e) {
				}
			} else {
				i = i + 1;
				System.out.println(Thread.currentThread().getName() + "-create-" + i);
				notify();
				this.created = true;
			}
		}
	}
	
	public void consume() {
		synchronized (this) {
			if (created) {
				System.out.println(Thread.currentThread().getName() + "-consume-" + i);
				notify();
				this.created = false;
			} else {
				try {
					wait();
				} catch (InterruptedException e) {
				}
			}
		}
	}
}

abstract class AbsFactory implements Runnable {
	protected Factory factory = null;
	
	public AbsFactory(Factory factory) {
		this.factory = factory;
	}
	
	abstract protected void execute();
	
	public void run() {
		while (true) {
			execute();
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
			}
		}
	}
}

class Producer extends AbsFactory {
	public Producer(Factory factory) {
		super(factory);
	}
	
	@Override
	protected void execute() {
		factory.create();
	}
}

class Consumer extends AbsFactory {
	public Consumer(Factory factory) {
		super(factory);
	}
	
	@Override
	protected void execute() {
		factory.consume();
	}
}

public class ProducerCustomer {
	public static void main(String[] args) {
		if (args.length == 0) {
			System.out .println("Usage:java com.wenhuisoft.chapter4.ProducerCustomer number");
			System.out.println("Please restart again....");
			System.exit(0);
		}
		int count = 0;
		try {
			count = Integer.parseInt(args[0]);
		} catch (Throwable t) {
			System.out.println("Please enter a integer type number...");
			System.exit(0);
		}
		final Factory factory = new Factory();
		for (int i = 0; i < count; i++) {
			new Thread(new Producer(factory)).start();
			new Thread(new Consumer(factory)).start();
		}
	}
}


猜你喜欢

转载自blog.csdn.net/chekongfu/article/details/43237365