java调用是什么_什么是Java可调用?

本文展示了如何使用Java的ExecutorService和Callable接口并行执行任务。通过创建一个固定大小的线程池,提交100个Callable任务,并利用Future获取每个任务的返回值。示例中,每个任务休眠一秒钟后返回执行该任务的线程名称。最后,主线程等待所有任务完成并打印结果,然后关闭ExecutorService。
摘要由CSDN通过智能技术生成

你可以查看这个

example:

在此示例中,Callable任务返回一秒钟后执行任务的线程的名称.我们使用Executor框架并行执行100个任务,并使用Future来获取提交任务的结果.

package com.journaldev.threads;

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 MyCallable implements Callable {

@Override

public String call() throws Exception {

Thread.sleep(1000);

//return the thread name executing this callable task

return Thread.currentThread().getName();

}

public static void main(String args[]){

//Get ExecutorService from Executors utility class, thread pool size is 10

ExecutorService executor = Executors.newFixedThreadPool(10);

//create a list to hold the Future object associated with Callable

List> list = new ArrayList>();

//Create MyCallable instance

Callable callable = new MyCallable();

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

//submit Callable tasks to be executed by thread pool

Future future = executor.submit(callable);

//add Future to the list, we can get return value using Future

list.add(future);

}

for(Future fut : list){

try {

//print the return value of Future, notice the output delay in console

// because Future.get() waits for task to get completed

System.out.println(new Date()+ "::"+fut.get());

} catch (InterruptedException | ExecutionException e) {

e.printStackTrace();

}

}

//shut down the executor service now

executor.shutdown();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值