Я завжди використовував Runnable, але недавно довелось перейти на Callable
Наведу простий приклад використання. Є офіційний приклад Using Callable to Return Results From Runnables
Я наводжу свій приклад і результат виконання.
Class Main – клас який запускає на виконання пул потоків а також відображає результат виконання.
Class Task – Клас який виконує завдання в пулі потоків
package callabletest;
/**
*
* @author ivi
*/
import java.util.*;
import java.util.concurrent.*;
import callabletest.Task;
public class Main {
public static void main(String[] args) throws Exception
{
ExecutorService pool = Executors.newFixedThreadPool(3);
Set<Future<Object>> set = new HashSet<Future<Object>>();
for(int i =0; i < 10; i ++)
{
Callable<Object> callable = callabletest.Task.getTask();
Future<Object> future = pool.submit(callable);
set.add(future);
}
for (Future<Object> future : set)
{
Object obj = future.get();
Task task = (Task) obj;
System.out.println("Test Return Values: "+task.getCurrent());
}
pool.shutdown();
}
}
package callabletest;
/**
*
* @author ivi
*/
import java.util.concurrent.*;
public class Task implements Callable
{
private static int counter = 0;
/**
* @return the counter
*/
public static int getCounter() {
return counter;
}
private int current = 0;
private Task()
{
counter ++;
this.current = counter;
}
public synchronized static Task getTask()
{
return new Task();
}
Результат
run: Task #1 Task #2 Task #3 Task #4 Task #5 Test Return Value: 1 Task #6 Task #7 Task #8 Task #9 Test Return Value: 6 Task #10 Test Return Value: 10 Test Return Value: 5 Test Return Value: 4 Test Return Value: 3 Test Return Value: 9 Test Return Value: 8 Test Return Value: 7 Test Return Value: 2 BUILD SUCCESSFUL (total time: 4 seconds)
Home
