24 paź 2013

Thread pool : Callable, Runnable, Executors

package com.areo;

import java.util.ArrayList;
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 Main {

	public static void main(String[] args) {
		executorWithRunnable();
		executorWithCallable();
	}

	private static void executorWithCallable() {

		ExecutorService pool = Executors.newFixedThreadPool(10);
		
		ArrayList<Future<Integer>> list 
			= new ArrayList<Future<Integer>>();
		
		for (int i = 0; i < 300; i++) {
			Future<Integer> submit = pool.submit(new MyCallable());
			list.add(submit);
		}
		
		//father results
		int result = 0;
		for (Future<Integer> future : list) {
			try {
				result += future.get();
			} catch (InterruptedException e) {
			} catch (ExecutionException e) {
			}
		}
		
		//result is 300
		System.out.println("Result: " + result);
		
	}

	private static void executorWithRunnable() {
		ExecutorService pool = Executors.newFixedThreadPool(10);
		
		for (int i = 0; i < 300; i++) {
			pool.execute(new MThread());
		}
		
		pool.shutdown();
	}

	//callable
	static class MyCallable implements Callable<Integer>{

		
		public Integer call() throws Exception {
			
			System.out.println("Calling!");
			return 1;
		}
		
	}
	
	//runnable
	static class MThread implements Runnable{

		public void run() {
			long id = Thread.currentThread().getId();
			System.out.println(String.format("Thread id = %d", id));
		}
		
	}
}