您的位置:首页 > 编程语言 > Java开发

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

2015-01-28 20:32 561 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: