`

工作队列池,线程池

    博客分类:
  • java
阅读更多
import java.util.LinkedList;



public class WorkQueue
{
    private final int nThreads;
    private final PoolWorker[] threads;//工作队列池,线程池
    private final LinkedList queue;//任务列表
  
    public WorkQueue(int nThreads)
    {
        this.nThreads = nThreads;
        queue = new LinkedList();
        threads = new PoolWorker[nThreads];
        for (int i=0; i<nThreads; i++) {
            threads[i] = new PoolWorker();
           // threads[i].setDaemon(true);
            threads[i].start();
        }
    }
   
    public void execute(Runnable r) {
        synchronized(queue) {
            queue.addLast(r);
            queue.notify();
        }
    }
    private class PoolWorker extends Thread {
        public void run() {
            Runnable r;
            while (true) {
                synchronized(queue) {
                    while (queue.isEmpty()) {
                        try
                        {
                            queue.wait();
                        }
                        catch (InterruptedException ignored)
                        {
                        }
                    }
                    r = (Runnable) queue.removeFirst();
                    System.out.println(r);
                }
                // If we don't catch RuntimeException,
                // the pool could leak threads
                try {
                    r.run();
                }
                catch (RuntimeException e) {
                    // You might want to log something here
                }
            }
        }
    }
    public static void main(String[] args) {
//申请5个备用工作线程池
    WorkQueue sdf = new WorkQueue(5);
//并发15个或者更多线程任务
    for (int i=0;i<100;i++) {
    sdf.execute(new taskThread());
}
   
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics