软件大师又要给弟子开小灶了,这次是线程和线程池。
软件大师正在闭目修炼, 最小的一名弟子慢慢走了进来。
线程池中的Worker线程: public class WorkerThread extends Thread { private BlockingQueue<Task> taskQueue = null; private boolean isStopped = false; //持有一个BlockingQueue的实例 public WorkerThread(BlockingQueue<Task> queue){ taskQueue = queue; } public void run(){ while(!isStopped()){ try{ Task task = taskQueue.take(); task.execute(); } catch(Exception e){ //log or otherwise report exception, //but keep pool thread alive. } } } ......略...... }
ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.execute(new Runnable() { public void run() { System.out.println("Asynchronous task"); } }); executorService.shutdown();
来源:码农翻身