WEB开发网
开发学院软件开发Java 多线程设计模式 -- ProducerConsumer 阅读

多线程设计模式 -- ProducerConsumer

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示:放蛋糕的桌子 Java代码publicclassTable{privatefinalString[]buffer;privateinttail;/下一个放put的地方privateinthead;//下一个放的take地方privateintcount;//buffer内的蛋糕数publicTable(intcount

放蛋糕的桌子

Java代码   

public class Table { 
  private final String[] buffer; 
  private int tail; /下一个放put的地方 
  private int head; //下一个放的take地方 
  private int count; // buffer内的蛋糕数 
  public Table(int count) { 
    this.buffer = new String[count]; 
    this.head = 0; 
    this.tail = 0; 
    this.count = 0; 
  } 
  // 放置蛋糕 
  public synchronized void put(String cake) throws InterruptedException { 
    System.out.println(Thread.currentThread().getName() + " puts " + cake); 
    while (count >= buffer.length) { 
      wait();//当蛋糕数大于容器大小是等待 
    } 
    buffer[tail] = cake; 
    tail = (tail + 1) % buffer.length; 
    count++; 
    notifyAll();//唤醒等待线程 
  } 
   
  
  // 取得蛋糕 
  public synchronized String take() throws InterruptedException { 
    while (count <= 0) { 
      wait();//当蛋糕数为0时,等待 
    } 
    String cake = buffer[head]; 
    head = (head + 1) % buffer.length; 
    count--; 
    notifyAll();//唤醒等待线程 
    System.out.println(Thread.currentThread().getName() + " takes " + cake); 
    return cake; 
  } 
}

吃线程

Java代码   

public class EaterThread extends Thread { 
  private final Random random; 
  private final Table table; 
  public EaterThread(String name, Table table, long seed) { 
    super(name); 
    this.table = table; 
    this.random = new Random(seed); 
  } 
  public void run() { 
    try { 
      while (true) { 
        String cake = table.take(); 
        Thread.sleep(random.nextInt(1000)); 
      } 
    } catch (InterruptedException e) { 
    } 
  } 
}

做线程

Java代码  

public class MakerThread extends Thread { 
  private final Random random; 
  private final Table table; 
  private static int id = 0; // 蛋糕的流水号(所有厨师共通) 
  public MakerThread(String name, Table table, long seed) { 
    super(name); 
    this.table = table; 
    this.random = new Random(seed); 
  } 
  public void run() { 
    try { 
      while (true) { 
        Thread.sleep(random.nextInt(1000)); 
        String cake = "[ Cake No." + nextId() + " by " + getName() + " ]"; 
        table.put(cake); 
      } 
    } catch (InterruptedException e) { 
    } 
  } 
  private static synchronized int nextId() { 
    return id++; 
  } 
}

测试线程

Java代码

public class Main {  
  public static void main(String[] args) {  
    Table table = new Table(3);   // 建立可以放置3個蛋糕的桌子  
    new MakerThread("MakerThread-1", table, 31415).start();  
    new MakerThread("MakerThread-2", table, 92653).start();  
    new MakerThread("MakerThread-3", table, 58979).start();  
    new EaterThread("EaterThread-1", table, 32384).start();  
    new EaterThread("EaterThread-2", table, 62643).start();  
    new EaterThread("EaterThread-3", table, 38327).start();  
  } 

Tags:线程 设计模式 ProducerConsumer

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接