ExecutorService的任务调度

1、Callable 用submit方法实现Callable有返回值

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableTaskTimer {
public static void main(String[] args) throws Exception{
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<String>> resultList = new ArrayList<Future<String>>();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date beginDate = null;
Date endDate = null;
// 创建1000个任务并执行
for (int i = 0; i < 1000; i++) {
// 使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中
Future<String> future = executorService.submit(new TaskWithResult(i,0));
// 将任务执行结果存储到List中
resultList.add(future);
if(i == 0){
beginDate = df.parse(df.format(new Date()));
}else if(i == 999){
Thread.currentThread().sleep(1000);
endDate = df.parse(df.format(new Date()));
}
}
long l=beginDate.getTime()-endDate.getTime();
long day=l/(24*60*60*1000);
long hour=(l/(60*60*1000)-day*24);
long min=((l/(60*1000))-day*24*60-hour*60);
long s=(l/1000-day*24*60*60-hour*60*60-min*60);
System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
// 遍历任务的结果
for (Future<String> fs : resultList) {
try {
System.out.println(fs.get()); // 打印各个线程(任务)执行的结果
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
// 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。
executorService.shutdown();
}
}
}
}

class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
public TaskWithResult(int id,int temp) {
this.id = id;
}
public String call() throws Exception {
System.out.println("call()方法被自动调用,干活!!!             "+ Thread.currentThread().getName());
// 一个模拟耗时的操作
for (int i = 999999; i > 0; i--);
return "call()方法被自动调用,任务的结果是:" + id + "    "+ Thread.currentThread().getName();
}
}



2、Runnable 用execute方法实现Runnable,无返回值

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

public class RunnableTask { 
    public static void main(String[] args) { 
   ExecutorService executorService = Executors.newCachedThreadPool();
   for (int i = 0; i < 10; i++) { //开启1000个任务
            executorService.execute(new TestRunnable()); 
            System.out.println("任务:" + (i+1)); 
   } 
   executorService.shutdown(); 
    } 


class TestRunnable implements Runnable { 
    public void run() { 
        System.out.println("线程:"+Thread.currentThread().getName()); 
    } 
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值