一个线程执行多个任务,要按照顺序执行

一个线程执行多个任务,要按照顺序执行

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 一个线程执行多个任务,要按照顺序执行,怎么去实现?
 * 分析:
 *      多个人任务-->线程
 *      要按照顺序执行--》就需要排队,那就是队列
 *       一个给任务,一个执行任务--》涉及一个生产一个消费
 *      过渡:需要容器装任务来存储任务
 *      有两个线程,一放一取不是原子操作,所以涉及线程安全问题
 * @author qfl
 * 扩展:
 * 1)怎么实现一个阻塞式对列结构?
 * 2)怎么实现一个LruCache缓存结构(不依托于LikedList,HashMap来实现)?
 * lru:最近最少算法
 * 
 * 扩展问题:
 *
 */
public class TestIOBlocking {
    static int m=0;
    //主线程
    public static void main(String[] args) {
        System.out.println("开始!");
        //生产任务的
        TestExecutor t=new TestExecutor();
        for(int i=0;i<20;i++) {
            t.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("test"+TestIOBlocking.m++);
                }
            }); 
        }

    } 
}
class TestExecutor{
    public TestExecutor() {
        //创建对象就执行
        thread.start();
    }
    private static workThread thread=new workThread();
    //存储任务的容器,先设定存3个任务,这是一个阻塞的队列
    private static ArrayBlockingQueue<Runnable> queue=new ArrayBlockingQueue<Runnable>(3);

    //工作线程
    static class workThread extends Thread{
        @Override
        public void run() {
                //执行的任务,反复的取
            while(TestIOBlocking.m<=19) {
                try {
                    Runnable r=queue.take();//阻塞方法
                    r.run();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    //取任务的方法
    public void execute(Runnable r) {
        try {
            queue.put(r);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37835884/article/details/78586744