`

util.Concurrent-Callable&Future

    博客分类:
  • Java
 
阅读更多

 

多线程协作完成任务时用?如IO异步编程?

package thread.pool;

import java.util.Random;
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;
import java.util.concurrent.FutureTask;

/**
 * Only proceed if all tasks are completed 1. 当所有任务都执行完成后,做某事
 */
public class Concurrent_Callable {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		//使用Future接收任务执行后的结果
		Future<Object> future = threadPool.submit(new MyTask("task1"));
		
		try {
			Object result = future.get();
			//pass result to another processor
			System.out.println("Result is :" + result);
		} catch (InterruptedException | ExecutionException e) {
			//判断是否特定异常发生了
			if(e.getCause() instanceof IllegalStateException) {
				System.out.println("Random().nextInt(100) % 2 == 0");
			} else {
				e.printStackTrace();
			}
		}
		
		threadPool.shutdown();
	}

}

class MyTask implements Callable {
	
	private String name;
	
	public MyTask(String name) {
		this.name = name;
	}
	
	public Object call() throws Exception {
		// doing something here ...
		Thread.sleep(2000);
		if(new Random().nextInt(100)%2==0) {
			throw new IllegalStateException();
		}
		
		// after task done,return result
		return name + " Done!";
	}
}


 

 

package thread.pool;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * Pass task results to other processor as soon as possible or do something else
 * while tasks are executing 2. 尽快将已经完成任务的结果传递给另外的线程处理
 */
public class Concurrent_CallableCompletion {

	public static void main(String[] args) {
		//创建线程池
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		//创建ExecutorCompletionService
		ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<Object>(threadPool);
		
		
		//提交若干任务到ExecutorCompletionService中
		for(int i=1;i<10;i++)
			completionService.submit(new OtherTask("task"+i));
		
		for(int i=1;i<10;i++) {
			try {
					//获取下一个完成的任务,如果没有,则阻塞
					Future<Object> future = completionService.take();
					Object result = future.get();
					
					//here: pass result to another processor
					System.out.println("Result is :" + result);
			} catch (InterruptedException | ExecutionException e) {
				//判断异常来源,进行特殊处理
				if(e.getCause() instanceof IllegalStateException) {
					System.out.println("Something bad happen! Random().nextInt(100) % 2 == 0");
				} else {
					e.printStackTrace();
				}
			}
		}
		
		threadPool.shutdown();
	}


}

class OtherTask implements Callable {
	
	private String name;
	
	public OtherTask(String name) {
		this.name = name;
	}
	
	public Object call() throws Exception {
		// doing something here ...
		Thread.sleep(2000);
		if(new Random().nextInt(100)%2==0) {
			throw new IllegalStateException();
		}
		
		// after task done,return result
		return name + " Done!";
	}
}


 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics