最精简的java 线程池与任务队列

最精简的java 线程池与任务队列

 

 1 import java.util.*;
 2 public class WorkQueue
 3 {
 4    private final int nThreads;//线程池的大小
 5    private final PoolWorker[] threads;//用数组实现线程池
 6    private final LinkedList queue;//任务队列
 7 
 8   public WorkQueue(int nThreads){
 9      this.nThreads = nThreads;
10      queue = new LinkedList();
11      threads = new PoolWorker[nThreads];
12 
13       for (int i=0; i<nThreads; i++) {
14          threads[i] = new PoolWorker();
15          threads[i].start();//启动所有工作线程
16       }
17   }
18 
19   public void execute(Runnable r) {//执行任务
20     synchronized(queue) {
21             queue.addLast(r);
22             queue.notify();
23     }
24   }
25 
26   private class PoolWorker extends Thread {//工作线程类
27         public void run() {
28                Runnable r;
29                while (true) {
30                     synchronized(queue) {
31                       while (queue.isEmpty()) {//如果任务队列中没有任务,等待
32                         try{
33                           queue.wait();
34                         }catch (InterruptedException ignored){}
35                       }   
36                        r = (Runnable) queue.removeFirst();//有任务时,取出任务
37                    }
38                    try {
39                        r.run();//执行任务
40                    }catch (RuntimeException e) {
41                       // You might want to log something here
42                   }
43               }
44       }
45    }
46 
47 
48  public static void main(String args[]){
49       WorkQueue wq=new WorkQueue(10);//10个工作线程
50       Mytask r[]=new Mytask[20];//20个任务
51   
52       for(int i=0;i<20;i++){
53            r[i]=new Mytask();
54            wq.execute(r[i]);
55       }      
56  }
57 }
58 class Mytask implements Runnable{//任务接口
59          public void run(){
60               String name=Thread.currentThread().getName();
61               try{
62                   Thread.sleep(100);//模拟任务执行的时间
63               }catch(InterruptedException e){}
64               System.out.println(name+" executed OK");
65          }
66   }

 

 

 

    原文作者:null7
    原文地址: http://www.cnblogs.com/null7/archive/2012/09/20/2696108.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞