生产者消费者形式,并发采用ReentrantLock
生产者消费者模式,并发采用ReentrantLock
package org.hkw.multithread; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; 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(); c.interrupt(); c2.interrupt(); p.interrupt(); p2.interrupt(); } } class Storehouse { static final int STATUS_EMPETY = 0; static final int STATUS_FULL = 1; boolean isClosed = false; String item; int status; Lock lock = new ReentrantLock(); 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 void produce(String name) throws InterruptedException { lock.lockInterruptibly(); try { if (isEmpty()) { String item = name + " fill"; System.out.println(name + " produce item:" + item); setItem(item); } } finally { lock.unlock(); } } public void consum(String name) throws InterruptedException { lock.lockInterruptibly(); try { if (!isEmpty()) { System.out.println(name + " consum item:" + house.getItem()); } } finally { lock.unlock(); } } } class Producer implements Runnable { Storehouse house = Storehouse.getInstance(); String name; public Producer(String name) { this.name = name; } @Override public void run() { System.out.println(name + " producer start"); while (!Thread.currentThread().isInterrupted() && !house.isClosed()) { try { house.produce(name); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println(name + " producer interrupted"); Thread.currentThread().interrupt(); } } System.out.println(name + " producer end"); } } class Consumer implements Runnable { Storehouse house = Storehouse.getInstance(); String name; public Consumer(String name) { this.name = name; } @Override public void run() { System.out.println(name + " cosumer start"); while (!Thread.currentThread().isInterrupted() && !house.isClosed()) { try { house.consum(name); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println(name + " cosumer interrupted"); Thread.currentThread().interrupt(); } } System.out.println(name + " consumer end"); } }