Java 自定义 线程池与任务队列

说明:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lovoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值