JAVA多线程的四种实现方式

来源:互联网 发布:fm2017最新数据库 编辑:程序博客网 时间:2024/06/01 16:49

1.继承Thread类

2.实现Runnable接口

3.实现Callable接口,通过FutureTask包装器来创建线程

Callable<V>的实现类:

public class MyCallableThread implements Callable<Integer> {@Overridepublic Integer call() throws Exception {int count = 0;for (int i = 0; i <= 100; i++) {System.out.println("Thread Name="+Thread.currentThread().getName());count += i;}return count;}}


目标测试类:

public class MyTestCallable {public static void main(String[] args) {MyCallableThread mThread = new MyCallableThread();// 执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果// FutureTask<Integer>是一个包装器FutureTask<Integer> oneTask = new FutureTask<Integer>(mThread);//由FutureTask<Integer>创建一个Thread对象:   Thread oneThread = new Thread(oneTask);   oneThread.start(); // 接收线程运算后的结果Integer sum =0;try {// 等所有线程执行完,获取值,因此FutureTask 可用于 闭锁sum = oneTask.get();System.out.println("-----------------------------");System.out.println("sum = "+sum);} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}



4.使用线程池(ExecutorService)创建线程

调用实例(rt.jar中):

  private final static ExecutorService executorService = Executors.newCachedThreadPool();@Overridepublic DataApplySyncRespDto sync(DataApplySyncReqDto request) {DataApplySyncRespDto response = new DataApplySyncRespDto();//......// 保存成功,开始发送短信final List<DataApplyDto> dataApplyDtoList = request.getDataApplys();executorService.execute(new Runnable() {@Overridepublic void run() {for(DataApplyDto apply:dataApplyDtoList){String mobile = apply.getContactMobile();for(DataNodeDto node:apply.getDataNodes()){String smsContent = xzspSmsSendService.getSmsContent(apply.getAffairName(), node.getNodeName(), node.getNodeResult(), apply.getSuid());xzspSmsSendService.sendSms(mobile, smsContent);}}}});response.setRespCode(SysRespConstants.SUCCESS.getCode());response.setMemo(SysRespConstants.SUCCESS.getName());//......return response;}




原创粉丝点击