任务队列_单线程_异步
多任务--> 单线程处理 模拟打印机
比如:一台打印机接收到很多task ,但是打印机只有一个Thread。不能同时打印。
这个打印机,在打印的时候不能接收新任务!!!
import java.util.LinkedList; public class Main { private static Thread thread; private static LinkedList<Runnable> list = new LinkedList<Runnable>(); static int test = 0; public static void main(String[] args) { final long time = System.currentTimeMillis(); for (int i = 0; i < 20; i++) { tastEvent(new Runnable() { public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("第" + (++test) + ("个任务 耗时:" + (System.currentTimeMillis() - time))); } }); } } public static void tastEvent(Runnable r) { synchronized (list) { list.add(r); } if (thread == null) { thread = new Thread(run); thread.start(); } } static Runnable run = new Runnable() { @Override public void run() { synchronized (list) { while (!list.isEmpty()) { // new Thread(list.poll()).start(); list.poll().run(); } thread = null; } } }; }

浙公网安备 33010602011771号