示例代码:
package model; import java.util.Arrays; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; class 生产者 implements Runnable{ private BlockingQueue<String> drop; private List<String> messages =Arrays.asList("aaaaa","bbbbb","ccccc","ddddd","eeeee"); public 生产者(BlockingQueue<String> d){ this.drop=d; } public void run() { try { for(String s:messages){ System.out.println("--------------"+s); drop.put(s); } drop.put("完成"); } catch (Exception e) { e.printStackTrace(); } } } class 消费者 implements Runnable{ private BlockingQueue<String> drop; public 消费者(BlockingQueue<String> d){ this.drop=d; } public void run() { try { String msg; while(!((msg = drop.take()).equals("完成"))){ System.out.println(msg); } } catch (Exception e) { e.printStackTrace(); } } } public class 生产者消费者 { public static void main(String[] args) { BlockingQueue<String> drop=new ArrayBlockingQueue<String>(3,true); new Thread(new 生产者(drop)).start(); new Thread(new 消费者(drop)).start(); } }