說明:
1)使用了隊列的先進先出思想
2)在執行的時候添加線程
3)在ThreadQueue 裡實現從隊列裡取出線程
/** * * @Project JavaDemos * @Package com.java.thread * @author chenlin * @version 1.0 * @Date 2011年6月12日 */public class WorkQueue { private int threadCounts;// 線程池的大小 private ThreadQueue[] threads;// 用數組實現線程池 private LinkedList queue;// 任務隊列 public WorkQueue(int threadCounts) { this.threadCounts = threadCounts; this.threads = new ThreadQueue[threadCounts]; this.queue = new LinkedList(); for (int i = 0; i < threadCounts; i++) { threads[i] = new ThreadQueue(); threads[i].start();// 啟動所有背景工作執行緒 } } public void execute(Runnable r) { synchronized (queue) { queue.addLast(r); queue.notify(); } } private class ThreadQueue extends Thread {// 背景工作執行緒類 @Override public void run() { Runnable r; while (true) { synchronized (queue) { // while (queue.isEmpty()) { try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } r = (Runnable) queue.removeFirst();// 有任務時,取出任務 } r.run(); } } } /** * 在靜態方法裡調用內部類必須是靜態 */ static class Mytask implements Runnable {// 任務介面 public void run() { String name = Thread.currentThread().getName(); try { Thread.sleep(100);// 類比任務執行的時間 } catch (InterruptedException e) { } System.out.println(name + " executed OK"); } } public static void main(String[] args) { WorkQueue wq = new WorkQueue(10);// 10個背景工作執行緒 Mytask r[] = new Mytask[20];// 20個任務 for (int i = 0; i < 20; i++) { r[i] = new Mytask(); wq.execute(r[i]); } }}
運行結果:
Thread-2 executed OK
Thread-6 executed OK
Thread-1 executed OK
Thread-5 executed OK
Thread-9 executed OK
Thread-7 executed OK
Thread-4 executed OK
Thread-8 executed OK
Thread-3 executed OK
Thread-0 executed OK
Thread-2 executed OK
Thread-5 executed OK
Thread-1 executed OK
Thread-9 executed OK
Thread-7 executed OK
Thread-6 executed OK
Thread-4 executed OK
Thread-8 executed OK
Thread-3 executed OK
Thread-0 executed OK