java中什么是调用,什么是可调用Java中?

本文通过一个示例详细介绍了Java中的Callable接口,展示了如何创建Callable任务并使用ExecutorService执行。Callable任务在执行后能返回一个结果,与Runnable不同。在示例中,100个Callable任务被并行执行,每个任务休眠1秒后返回执行线程的名字。使用Future对象可以获取每个任务的结果。这个概念在多线程编程和并发处理中非常关键。
摘要由CSDN通过智能技术生成

The title pretty much sums it.

I want to know the concept and idea of callable . I have read a question here on difference between callable and runnable. but no one show code and give detail what a callable is. I don't want to know the difference between them. I want to know ,

What is a callable ?

When to use them and how to use them .

When they come in action for

Android.

解决方案

You can check this example:

In this example Callable task returns the name of thread executing the task after one second. We are using Executor framework to execute 100 tasks in parallel and use Future to get the result of the submitted tasks.

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值