java多线程封装_Java 多线程处理任务的封装

最近项目很多地方使用多线程处理一些任务,逻辑代码和java多线程处理代码混合在一起,造成代码的可读性超级差,现在把Java多线程相关的处理抽出来,方面代码中重复使用。抽的不好,欢迎大家拍砖

使用方法很简单,有两种使用方法

1.直接传递一批任务给到多线程处理方法,返回处理结果

代码如下:/**

* Created with IntelliJ IDEA.

* 测试多线程处理任务

* className: TaskMulThreadServiceTest

*

* @version 1.0

* Date Time: a

*@author: ddys

*/public class TaskMulThreadServiceTest extends TestCase implements ITaskHandle{

public void testExecute() throws Exception {

String [] taskItems = new String[100];

for (int i=0;i<100;i++){

taskItems[i]="任务"+i;

}

IMulThreadService mulThreadService = new TaskMulThreadService(this);

long start = System.currentTimeMillis();

List result = mulThreadService.execute(taskItems);

for (Boolean e : result){

if(!e){

System.out.println("任务处理失败");

}

}

System.out.println("所有任务处理完成,耗时"+(System.currentTimeMillis()-start)+",任务成功数"+result.size());

}

/**

* Created with IntelliJ IDEA.

* 执行任务,返回所有执行的结果

* className: TaskMulThreadService

*

* @author: ddys

* @version 1.0

* Date Time:

*/

public Boolean execute(String s) {

System.out.println(Thread.currentThread().getId()+"线程正在处理"+s);

return true;

}

}

2.附带一个查询任务的方法,实现这个查询任务方法和业务处理方法,然后执行返回处理结果

代码如下:ate Time: a

*@author: XWK

*/

public class SelectTaskMulThreadServiceTest extends TestCase implements ISelectTask{

public void testExecute() throws Exception {

IMulThreadService mulThreadService = new SelectTaskMulThreadService(this);

long start = System.currentTimeMillis();

List result = mulThreadService.execute();

for (Boolean e : result){

if(!e){

System.out.println("任务处理失败");

}

}

System.out.println("所有任务处理完成,耗时"+(System.currentTimeMillis()-start)+",任务成功数"+result.size());

}

/**

* Created with IntelliJ IDEA.

* 执行任务,返回所有执行的结果

* className: TaskMulThreadService

*

* @author: ddys

* @version 1.0

* Date Time:

*/

public Boolean execute(String s) {

System.out.println(Thread.currentThread().getId()+"线程正在处理"+s);

return true;

} /**

* @param 'a 传递参数

* @return a 回类型

* @throws

* @Title: a

* @Description: 获取一批任务

* @author ddys

* @date 2015-11-15 21:09

*/

public String[] getTaskItem() {

String [] taskItems = new String[100];

for (int i=0;i<100;i++){

taskItems[i]="任务"+i;

}

return taskItems;

}

}

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值