多线程-实现多线程三种方式

2021-03-01 04:28

阅读:659

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 (Future future:futureList) {
if(future.isDone()) {
System.out.println(i+"结果是" + future.get());
i++;
}
}
executorService.shutdown();
}
}


评论


亲,登录后才可以留言!