`

使用同步队列解决任务协作问题

阅读更多
Java API里面提供了许多同步队列,你可以使用它来解决任务协作问题。同步队列在任何时刻都只允许一个任务插入或移除元素。例子如下:


===============基本线程类

public class LiftOff implements Runnable {   
     protected int countDown = 10;   
      private static int taskCount = 0;   
     private final int id = taskCount++;   
    
      public LiftOff() {   
      }   
    
      public LiftOff(int countDown) {   
          this.countDown = countDown;   
      }   
    
        public String status() {   
          return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "),";   
      }   
    
      @Override  
      public void run() {   
         while (countDown-- > 0) {   
              System.out.println(status());   
              Thread.yield();   
          }   
     }   
   
 }


==============================

public class LiftOffRunner implements Runnable{

 private BlockingQueue rockets;
 
 public LiftOffRunner(BlockingQueue queue) {
  // TODO Auto-generated constructor stub
  rockets=queue;
 }
 
 public void add(LiftOff lo){
  try {
   rockets.put(lo);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  //BloIllegalStateException
 }
 
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  try {
   while(!Thread.interrupted()){
    LiftOff rocket=rockets.take();
    rocket.run();
   }
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
      System.out.println("Weaking From take()");
  }
  System.out.println(" Exiting LiftOffRunner()");
 }
}

=========================测试类TestBlockingQueues

public class TestBlockingQueues {

 static void getKey(){
  try {
   new BufferedReader(new InputStreamReader(System.in)).readLine();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   throw new RuntimeException(e);
  }
  
 }
 
 
 static void getKey(String message){
  System.out.println(""+message);
  getKey();
 }
 
 
 static void test(String msg,BlockingQueue queue)
 {
  System.out.println(msg);
  LiftOffRunner runner=new LiftOffRunner(queue);
  Thread t=new Thread(runner);
  t.start();
  for(int i=0;i());
  test("ArrayBlockingQueue",new ArrayBlockingQueue(3));
  test("SynchronousQueue",new SynchronousQueue());
  
  
 }
}
===================测试结果如下:



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics