淺談java.util.concurrent包的併發處理(轉)
java.util.concurrent下主要的接口和類:
Executor:具體Runnable任務的執行者。
ExecutorService:一個線程池管理者,其實現類有多種,比如普通線程池,定時調度線程池ScheduledExecutorService等,我們能把一個
Runnable,Callable提交到池中讓其調度。
Future:是與Runnable,Callable進行交互的接口,比如一個線程執行結束後取返回的結果等等,還提供了cancel終止線程。
BlockingQueue:阻塞隊列。
下面我寫一個簡單的事例程序:
FutureProxy.java
- package org.test.concurrent;
- /** *//**
- * <p>Title: LoonFramework</p>
- * <p>Description:利用Future模式進行處理</p>
- * <p>Copyright: Copyright (c) 2007</p>
- * <p>Company: LoonFramework</p>
- * @author chenpeng
- * @email:[email protected]
- * @version 0.1
- */
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.ThreadFactory;
- public abstract class FutureProxy<T> {
- private final class CallableImpl implements Callable<T> {
- public T call() throws Exception {
- return FutureProxy.this.createInstance();
- }
- }
- private static class InvocationHandlerImpl<T> implements InvocationHandler {
- private Future<T> future;
- private volatile T instance;
- InvocationHandlerImpl(Future<T> future){
- this.future = future;
- }
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- synchronized(this){
- if(this.future.isDone()){
- this.instance = this.future.get();
- }else{
- while(!this.future.isDone()){
- try{
- this.instance = this.future.get();
- }catch(InterruptedException e){
- Thread.currentThread().interrupt();
- }
- }
- }
- return method.invoke(this.instance, args);
- }
- }
- }
- /** *//**
- * 實現java.util.concurrent.ThreadFactory接口
- * @author chenpeng
- *
- */
- private static final class ThreadFactoryImpl implements ThreadFactory {
- public Thread newThread(Runnable r) {
- Thread thread = new Thread(r);
- thread.setDaemon(true);
- return thread;
- }
- }
- private static ExecutorService service = Executors.newCachedThreadPool(new ThreadFactoryImpl());
- protected abstract T createInstance();
- protected abstract Class<? extends T> getInterface();
- /** *//**
- * 返回代理的實例
- * @return
- */
- @SuppressWarnings("unchecked")
- public final T getProxyInstance() {
- Class<? extends T> interfaceClass = this.getInterface();
- if (interfaceClass == null || !interfaceClass.isInterface()) {
- throw new IllegalStateException();
- }
- Callable<T> task = new CallableImpl();
- Future<T> future = FutureProxy.service.submit(task);
- return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),
- new Class<?>[] { interfaceClass }, new InvocationHandlerImpl(future));
- }
- }
package org.test.concurrent;
/** *//**
* <p>Title: LoonFramework</p>
* <p>Description:利用Future模式進行處理</p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: LoonFramework</p>
* @author chenpeng
* @email:[email protected]
* @version 0.1
*/
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
public abstract class FutureProxy<T> {
private final class CallableImpl implements Callable<T> {
public T call() throws Exception {
return FutureProxy.this.createInstance();
}
}
private static class InvocationHandlerImpl<T> implements InvocationHandler {
private Future<T> future;
private volatile T instance;
InvocationHandlerImpl(Future<T> future){
this.future = future;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
synchronized(this){
if(this.future.isDone()){
this.instance = this.future.get();
}else{
while(!this.future.isDone()){
try{
this.instance = this.future.get();
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
}
return method.invoke(this.instance, args);
}
}
}
/** *//**
* 實現java.util.concurrent.ThreadFactory接口
* @author chenpeng
*
*/
private static final class ThreadFactoryImpl implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}
private static ExecutorService service = Executors.newCachedThreadPool(new ThreadFactoryImpl());
protected abstract T createInstance();
protected abstract Class<? extends T> getInterface();
/** *//**
* 返回代理的實例
* @return
*/
@SuppressWarnings("unchecked")
public final T getProxyInstance() {
Class<? extends T> interfaceClass = this.getInterface();
if (interfaceClass == null || !interfaceClass.isInterface()) {
throw new IllegalStateException();
}
Callable<T> task = new CallableImpl();
Future<T> future = FutureProxy.service.submit(task);
return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),
new Class<?>[] { interfaceClass }, new InvocationHandlerImpl(future));
}
}
Test.java
- package org.test.concurrent;
- import java.util.Calendar;
- /** *//**
- * <p>Title: LoonFramework</p>
- * <p>Description:</p>
- * <p>Copyright: Copyright (c) 2007</p>
- * <p>Company: LoonFramework</p>
- * @author chenpeng
- * @email:[email protected]
- * @version 0.1
- */
- interface DateTest{
- String getDate();
- }
- class DateTestImpl implements DateTest{
- private String _date=null;
- public DateTestImpl(){
- try{
- _date+=Calendar.getInstance().getTime();
- //設定五秒延遲
- Thread.sleep(5000);
- }catch(InterruptedException e){
- }
- }
- public String getDate() {
- return "date "+_date;
- }
- }
- class DateTestFactory extends FutureProxy<DateTest>{
- @Override
- protected DateTest createInstance() {
- return new DateTestImpl();
- }
- @Override
- protected Class<? extends DateTest> getInterface() {
- return DateTest.class;
- }
- }
- public class Test{
- public static void main(String[] args) {
- DateTestFactory factory = new DateTestFactory();
- DateTest[] dts = new DateTest[100];
- for(int i=0;i<dts.length;i++){
- dts[i]=factory.getProxyInstance();
- }
- //遍歷執行
- for(DateTest dt : dts){
- System.out.println(dt.getDate());
- }
- }
- }