- package org.hkw.multithread;
- public class ThreadDCTest {
- public static void main(String[] args) {
- Thread p = new Thread(new Producer("p1"));
- Thread p2 = new Thread(new Producer("p2"));
- Thread c = new Thread(new Consumer("c1"));
- Thread c2 = new Thread(new Consumer("c2"));
- p.start();
- p2.start();
- c.start();
- c2.start();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // Storehouse.getInstance().close();
- p.interrupt();
- p2.interrupt();
- c.interrupt();
- c2.interrupt();
- }
- }
- class Storehouse {
- static final int STATUS_EMPETY = 0;
- static final int STATUS_FULL = 1;
- boolean isClosed = false;
- String item;
- int status;
- private static Storehouse house = new Storehouse();
- private Storehouse() {
- }
- public static Storehouse getInstance() {
- return house;
- }
- public String getItem() {
- status = STATUS_EMPETY;
- return item;
- }
- public void setItem(String item) {
- status = STATUS_FULL;
- this.item = item;
- }
- public int getStatus() {
- return status;
- }
- public boolean isEmpty() {
- return status == STATUS_EMPETY;
- }
- public boolean isClosed() {
- return isClosed;
- }
- public void close() {
- isClosed = true;
- }
- public synchronized void produce(String name) throws InterruptedException
- {
- if (isEmpty()) {
- String item = name + " fill";
- System.out.println(name + " produce item:" + item);
- setItem(item);
- notifyAll();
- } else {
- wait();
- }
- }