一个线程执行多个任务,要按照顺序执行
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();
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) {
e.printStackTrace();
}
}
}
}
public void execute(Runnable r) {
try {
queue.put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}