首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

java 线程池示范(自己实现的参考别人的代码)

2012-09-27 
java 线程池示例(自己实现的参考别人的代码)一般一个简单线程池至少包含下列组成部分线程池管理器(ThreadP

java 线程池示例(自己实现的参考别人的代码)


一般一个简单线程池至少包含下列组成部分

线程池管理器(ThreadPoolManager):用于创建并管理线程池工作线程(WorkThread): 线程池中线程任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。任务队列:用于存放没有处理的任务。提供一种缓冲机制。

?

package com.yulin.threadpool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

/*
?*? 线程池管理器(PoolManager):用于创建并管理线程池,采用单例模式
?*
?*/
public class PoolManage {
?? ?public static PoolManage mPool=new PoolManage();
?? ?public final int max_pool =2;
?? ?public final int max_Tasks = 15;
?? ?public static ArrayList<Worker> init_pools;
?? ?private int GetIdleThreadPollTime=50;//获取空闲线程轮询间隔时间,可配置
?? ?private TaskMonitorThread mainThread;//任务监测线程

?? ?static {
?? ??? ?init_pools = new ArrayList(1);
?? ?}

?? ?public static PoolManage getInstance() {
?? ??? ?if (mPool == null) {
?? ??? ??? ?mPool = new PoolManage();
?? ??? ?}

?? ??? ?return mPool;
?? ?}
?? ?
?? ?
?? ?
?? ?//获取空闲线程
?? ?public? Worker getIdleThread(){
?? ??? ?Worker working =null;
?? ??? ?while(true){
?? ??? ??? ?synchronized(init_pools){
?? ??? ??? ??? ?for (int i = 0; i < max_pool; i++) {
?? ??? ??? ??? ??? ?//Worker working = init_pools.get(i);
?? ??? ??? ??? ??? ?working = init_pools.get(i);
?? ??? ??? ??? ??? ?if (!working.isrunning) {
?? ??? ??? ??? ??? ?//?? ?System.out.println("工作将由闲置线程" + working.getThreadTag() + "执行");
?? ??? ??? ??? ??? ??? ?return working;
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ??? ?try {
?? ??? ??? ??? ?Thread.sleep(5000);//放弃CPU,若干时间后重新获取空闲线程
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?
?? ??? ?
?? ?}
?? ?public void init() {
?? ??? ?System.out.println("线程池初始化开始。。。");
?? ??? ?Worker worker = null;
?? ??? ?for (int i = 0; i < this.max_pool; i++) {
?? ??? ??? ?worker = new Worker("initThread"+i);
?? ??? ??? ?init_pools.add(worker);
?? ??? ??? ?worker.start();
?? ??? ?}
?? ??? ?mainThread=new? TaskMonitorThread();
?? ??? ?mainThread.start();
?? ??? ?System.out.println("结束初始化线程池...");

?? ?}
?? ?

}

?

?

package com.yulin.threadpool;

import java.util.LinkedList;

/**
?*? 任务管理器
?*? 1、添加任务
?*? 2、监测是否有新任务
?*/
public class TaskManager {
??? public static LinkedList<WorkTask> workqueue =new LinkedList<WorkTask>();// 缓冲队列
??? /**
??? ?* 向工作队列中加入一个任务,由工作线程去执行该任务
??? ?*
??? ?* @param task
??? ?*/
??? public synchronized static void addTask(WorkTask worktask) {
??? ??? if (worktask != null &&workqueue.size()<15) {
??? ??? ??? workqueue.add(worktask);
??? ??? }
??? }
??? /*[com.yulin.threadpool.WorkTaskImp@44f4ac30,
??? ?com.yulin.threadpool.WorkTaskImp@44f4ad60,
??? ?com.yulin.threadpool.WorkTaskImp@44f4ae00,
??? ?com.yulin.threadpool.WorkTaskImp@44f4aea0,
??? ?com.yulin.threadpool.WorkTaskImp@44f4af40]*/

??? /**
??? ?* 从工作队列中取出一个任务
??? ?*
??? ?* @return
??? ?* @throws InterruptedException
??? ?*/
??? public synchronized static WorkTask getTask() throws InterruptedException {
??? ??? while (workqueue.size() >0) {
??? ??? ??? return (WorkTask) workqueue.removeFirst();
??? ??? }
??? ??? return null;
??? }
}

?

package com.yulin.threadpool;

/**
?* 任务检测线程类 检测空闲线程并检测待运行任务
?*/
public final class TaskMonitorThread extends Thread {
??? //private PoolManage threadPool;
??? private int GetWorkTaskPollTime = 10;// 监测任务轮询时间,可配置
??? /*public TaskMonitorThread(PoolManage pool) {
??? ??? System.out.println("正在创建任务监测线程...");
??? ??? this.threadPool = pool;
??? }*/
??? public TaskMonitorThread() {
??? ??? System.out.println("正在创建任务监测线程...");
??? }
??? @Override
??? public void run() {
??? ??? // TODO Auto-generated method stub
??? ??? while (true) {
??? ??? ???
??? ??? ??? try {
??? ??? ??? ??? WorkTask task = TaskManager.getTask();
??? ??? ??? ??? if (task == null) {
??? ??? ??? ??? ??? try {
??? ??? ??? ??? ??? ??? Thread.sleep(5000);
??? ??? ??? ??? ??? } catch (InterruptedException e) {
??? ??? ??? ??? ??? ??? // TODO Auto-generated catch block
??? ??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? ??? }

??? ??? ??? ??? } else {
??? ??? ??? ??? ??? Worker t = PoolManage.getInstance().getIdleThread();// 获取空闲线程
??? ??? ??? ??? ??? ?System.out.println("Worker.toString()=============================>?"+t.toString());
??? ??? ??? ??? ??? if (t == null)
??? ??? ??? ??? ??? ??? break;
??? ??? ??? ??? ??? ?t.setWorkTask(task);// 设置线程任务
??? ??? ??? ??? ??? ?System.out.println("task.toString()=============================>?"+task.toString());
??? ??? ??? ??? ??? ?t.setIsRunning(true);//激活空闲线程
??? ??? ??? ??? ??? ?System.out.println("Worker.toString()=============================>?"+t.getIsrunning());
??? ??? ??? ??? ??? // try {
??? ??? ??? ??? ??? //Thread.sleep(GetWorkTaskPollTime);
??? ??? ??? ??? ??? //
??? ??? ??? ??? }

??? ??? ??? } catch (InterruptedException e) {
??? ??? ??? ??? // TODO Auto-generated catch block
??? ??? ??? ??? e.printStackTrace();
??? ??? ??? }
??? ??? }
??? }


}

?

package com.yulin.threadpool;
/**
?* 工作线程(WorkThread): 线程池中线程
?* @author yulin
?*
?*/
public class Worker extends Thread {
??? public boolean isrunning=false;
??? private WorkTask nowTask; // 当前任务
??? private Object threadTag;// 线程标识
??? //获取线程标识key
??? public Object getThreadTag() {
??? ??? return threadTag;
??? }?????
??? public synchronized void setWorkTask(WorkTask task) {
??? ??? this.nowTask = task;
??? }

??? public synchronized void setIsRunning(boolean flag) {
??? ??? this.isrunning = flag;
??? ??? if (flag) {
??? ??? ??? this.notify();
??? ??? }
??? }

??? public Worker(Object key) {
??? ??? System.out.println("正在创建工作线程...线程编号" + key.toString());
??? ??? this.threadTag = key;
??? ??? // this.state=CREATESTATE;
??? }

??? public boolean getIsrunning() {
??? ??? return isrunning;
??? }

??? public synchronized void run() {
??? ??? System.out.println("工作线程" +? this.getThreadTag()? + "初始化成功");
??? ??? while (true) {
??? ??? ??? if (!isrunning) {
??? ??? ??? ??? try {
??? ??? ??? ??? ??? System.out.println("工人" + this.getThreadTag() + "任务完成回归线程池");
??? ??? ??? ??? ??? this.wait();
??? ??? ??? ??? } catch (InterruptedException e) {
??? ??? ??? ??? ??? System.out.println("线程被阻挡");
??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? }
??? ??? ??? } else {
??? ??? ??? ??? //try {
??? ??? ??? ??? ??? nowTask.runTask();
??? ??? ??? ??? ??? setIsRunning(false);
??? ??? ??? ??? ??? System.out.println("工人" +this.getThreadTag()? + "开始工作");
??? ??? ??? ??? ??? //this.sleep(3000);
??? ??? ??? //} catch (InterruptedException e) {
??? ??? ??? ??? //??? e.printStackTrace();
??? ??? ??? ??? //}
??? ??? ??? ???
??? ??? ??? ??? //this.notify();
??? ??? ??? ??? //break;
??? ??? ??? }
??? ??? }
??? }
}

?

?

package com.yulin.threadpool;
/**
?* 任务接口
?* 继承它来定义自己具体的工作任务
?*/
public interface WorkTask {
??? ?public void runTask();//执行工作任务
??? ??? //public int compareTo(mJob job);
??? ?public void cancelTask();
??? ?public int getProgress();
}

?

package com.yulin.threadpool;

import android.util.Log;

/**
?* 任务类1
?* 正常执行的工作任务
?*/
public class WorkTaskAImp implements WorkTask {

??? protected String param;
??? public WorkTaskAImp(){
??? }
??? public WorkTaskAImp(String param){
??? ??? this.param=param;
??? }
??? @Override
??? public void runTask() {
??????? // TODO Auto-generated method stub
?????? // Log.v("=============>Task1", this.param);
??????? System.out.println("=============>Task1"+this.param);
??? }

??? @Override
??? public void cancelTask() {
??????? // TODO Auto-generated method stub
??????
??? }

??? @Override
??? public int getProgress() {
??????? // TODO Auto-generated method stub
??????? return 0;
??? }
???
}

?

package com.yulin.threadpool;

import android.util.Log;

/**
?* 任务类1
?* 正常执行的工作任务
?*/
public class WorkTaskImp implements WorkTask {

??? protected String param;
??? public WorkTaskImp(){
??? }
??? public WorkTaskImp(String param){
??? ??? this.param=param;
??? }
??? @Override
??? public void runTask() {
??????? // TODO Auto-generated method stub
??????? System.out.println("=============>Task0"+this.param);
??? }

??? @Override
??? public void cancelTask() {
??????? // TODO Auto-generated method stub
??????
??? }

??? @Override
??? public int getProgress() {
??????? // TODO Auto-generated method stub
??????? return 0;
??? }
???
}

?

最后是测试 类

?

package com.example.test;
?
import com.example.task.TaskManager;
import com.example.task.WorkTask;
import com.example.task.WorkTaskAImp;
import com.example.task.WorkTaskBImp;
import com.example.task.WorkTaskImp;
import com.example.thread.ThreadPool;
?
?
?
/**
?* 线程池测试类,测试功能如下:
?* 1、测试线程池创建功能
?* 2、测试处理并发请求功能
?* 3、测试关闭功能
?**/
public class TestThreadPool {
??? public static void main(String[] args){
??? ??? //创建线程池,开启处理请求服务
??? ??? final int threadCount=10;
??? ??? ThreadPool pool=ThreadPool.getInstance();
??? ??? pool.init(threadCount);
??? ??? //接收客户端请求
??? ??? WorkTask task1=new? WorkTaskAImp("执行超时任务1...");
??? ??? TaskManager.addTask(task1);
??? ??? final int requestCount=15;
??? ??? for(int i=0;i<requestCount;i++){
??? ??? ??? WorkTask task=new WorkTaskImp("执行第"+i+"个增加用户操作.....");
??? ??? ??? TaskManager.addTask(task);
??? ??? }
??? ??? /**/
??? }
}

热点排行