在Java中,当线程数量过多时开销会很大。针对任务数量多,任务执行时间短的情况我们引入线程池的概念。 线程池可以减少在创建和销毁线程上所花的时间及系统资源以及在线程切换间的系统资源开销 。 我们通过下面的例子来简单了解下线程池。首先创建一个线程池类,MyThreadPool,在该类中,创建保存任务的队列,保存线程的数组,建立执行任务的方法,并且创建一个池中工作线程类。然后建立一个任务类 MyTask 任务本身执行操作,再加上一个测试类Test。
package com.test; import java.util.LinkedList; /** * 线程池类 * @author hy * */ public class MyThreadPool { public LinkedList<MyTask> task_list; //保存任务的队列 public MyThread[] thread_list; //保存池中线程的数组 public MyTask task; // 创建线程,启动 execute方法 添加线程 public MyThreadPool(int threadcount){ //初始化池 task_list = new LinkedList<MyTask>(); thread_list = new MyThread[threadcount]; //创建线程 for(int i=0;i<threadcount;i++){ //创建新线程 MyThread work_thread = new MyThread(); work_thread.setName("第"+i+"个线程");//为创建的线程命名 thread_list[i] = work_thread;//添加线程到数组中 work_thread.start();//启动线程 System.out.println("第"+i+"个线程创建出来了"); } } /** 添加任务 */ public void addTask(MyTask task){ synchronized(task_list){ task_list.add(task);//添加任务 task_list.notify();//唤醒等待中的线程 } } /** * 池中工作线程类 */ class MyThread extends Thread{ public void run(){ while(true){ synchronized(task_list){ if(task_list.isEmpty()){ try { task_list.wait(); //线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } task = task_list.removeFirst(); //取出任务 } //注意,要写在synchronized(){}外,否则会报java.util.NoSuchElementException task.makeTask(); try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
package com.test; /** * 任务类 * @author hy * */ public class MyTask { private String name; public MyTask(String name){ this.name = name ; } public String name(){ return name; } public void makeTask(){ //获取当前线程 Thread current_thread = Thread.currentThread(); System.out.println(current_thread.getName()+"处理了任务 "+name); } }
package com.test; /** * 测试类 * @author hy * */ public class Test { public static void main(String[] args){ MyThreadPool thread_pool = new MyThreadPool(250); for(int i=0;i<500;i++){ MyTask task = new MyTask("第"+i+"个任务"); thread_pool.addTask(task); } } }