顺序队列实现任务以此执行-任务调度系列2

顺序队列实现任务以此执行的想法:

public class TaskManage {

    //任务队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10); 
     
    private boolean running = false;  
      
    public void start() {  
        running = true;  
        Thread t = new Thread(new OrderedJob());  
        t.start();  
    }  
  
    public void stop() {  
        running = false;  
    }  
    
    public void submit(Runnable task){
        try {
            if(queue.offer(task, 5000L, TimeUnit.MILLISECONDS) == false){
                System.out.println();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    class OrderedJob implements Runnable {  
          
        @Override  
        public void run() {  
            while (running) {  
                try {  
                    Runnable job = queue.poll(5000L, TimeUnit.MILLISECONDS);  
                    try {  
                        if (job != null)  
                            job.run();  
                    } catch (RuntimeException e) {  
                        // TODO: handle exception  
                    }  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }
}

 

posted on 2015-01-20 23:06  每当变幻时  阅读(682)  评论(0编辑  收藏  举报

导航