think in java - concurrency - Callable

# When to use Callable?java

If you want the task to produce a value when it's done.ide

public class CallableDemo {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		List<Future<String>> results = new ArrayList<Future<String>>();
		for (int i = 0; i < 10; i++) {
			results.add(pool.submit(new TaskWithResult(i)));
		}
		
		for (Future<String> future : results) {
			try {
				System.out.println(future.get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			} finally {
				pool.shutdown();
			}
		}
	}
}

class TaskWithResult implements Callable<String> {
	
	private int id;
	
	public TaskWithResult(int id) {
		this.id = id;
	}
	
	@Override
	public String call() throws Exception {
		return "id: " + id;
	}
}

# Future.isDone()fetch

query the Future object to see if it has completed.this


#Future.get()code

when the task is done, you can fetch the result using get(), or the call to get() will block until the result is ready.get


# how to convert a Runnable into Callable?it

Executors.callable(runnable);io

Executors.callable(runnable, result);
class

相關文章
相關標籤/搜索