多线程-实现多线程三种方式
2021-03-01 04:28
public class ThreadCallable implements Callable{
private String worker;
public ThreadCallable(String worker){
this.worker=worker;
}
public Boolean call() throws Exception {
System.out.println("线程:"+Thread.currentThread().getName()+ ",执行"+ worker);
Thread.sleep(1000);
return true;
}public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("可用线程池:"+Runtime.getRuntime().availableProcessors());
ExecutorService executorService= Executors.newFixedThreadPool(1);
List> callableList=new ArrayList >();
for(int i=0;i
callableList.add(new ThreadCallable("Worker"+i));
}
List> futureList= executorService.invokeAll(callableList);
int i=0;
for (Futurefuture:futureList) {
if(future.isDone()) {
System.out.println(i+"结果是" + future.get());
i++;
}
}
executorService.shutdown();
}
}
上一篇:Python 判断段质数
下一篇:【Python】图片有效性管理