当前位置:首页 > 开发 > 编程语言 > Java > 正文

生产者消费者问题(java)

发表于: 2011-09-14   作者:Brucegaochina   来源:转载   浏览:
摘要: 学习到线程这章,自己写了个生产者消费者问题。 模拟的是电脑的生产和消费。 package thread; class Computer { private int id; Computer(int id) { this.id = id; } //override the method toString() from Object public
学习到线程这章,自己写了个生产者消费者问题。
模拟的是电脑的生产和消费。
package thread;

class Computer {
	private int id;

	Computer(int id) {
		this.id = id;
	}
	
	//override the method toString() from Object
	public String toString() {
		return "Computer:[" + id + "]";
	}
}

class Factory {
	private int items = 0;
	Computer[] computer;

	Factory() {
		computer = new Computer[6];
	}

	public synchronized void push(Computer comp) {
		while (items == computer.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		computer[items++] = comp;
		// items++;
	}

	public synchronized Computer pop() {
		while (items == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		return computer[--items];
	}

}

class Ibm implements Runnable {
	Factory fac = null;

	Ibm(Factory f) {
		this.fac = f;
	}

	public void run() {
		for (int i = 0; i < 20; i++) {
			Computer com = new Computer(i);
			fac.push(com);
			System.out.println("IBM assemble one computer " + com);
			try {
				Thread.sleep((long) (Math.random()*100));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Kisters implements Runnable {
	Factory fac = null;

	Kisters(Factory f) {
		this.fac = f;
	}

	public void run() {
		for (int i = 0; i < 20; i++) {
			Computer com = fac.pop();
			System.out.println("Kisters consume one computer " + com);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

public class ProducerConsumer {

	public static void main(String[] args) {
		Factory fac = new Factory();
		Ibm ibm = new Ibm(fac);
		Kisters kis = new Kisters(fac);
		Thread t1 = new Thread(ibm);
		Thread t2 = new Thread(kis);
		t1.start();
		t2.start();
	}

}

生产者消费者问题(java)

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号