对线程池的初步了解

        在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);
		}
	}
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值