浅谈java.util.concurrent包的并发处理(转)

我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,而当针对高质量Java多线程并发程序设计时,为防止死蹦等现象的出现,比如使用java之前的wait()、notify()和synchronized等,每每需要考虑性能、死锁、公平性、资源管理以及如何避免线程安全性方面带来的危害等诸多因素,往往会采用一些较为复杂的安全策略,加重了程序员的开发负担.万幸的是,在JDK1.5出现之后,Sun大神终于为我们这些可怜的小程序员推出了java.util.concurrent工具包以简化并发完成。开发者们借助于此,将有效的减少竞争条件(race conditions)和死锁线程。concurrent包很好的解决了这些问题,为我们提供了更实用的并发程序模型。


java.util.concurrent下主要的接口和类:

Executor:具体Runnable任务的执行者。

ExecutorService:一个线程池管理者,其实现类有多种,比如普通线程池,定时调度线程池ScheduledExecutorService等,我们能把一个

Runnable,Callable提交到池中让其调度。

Future:是与Runnable,Callable进行交互的接口,比如一个线程执行结束后取返回的结果等等,还提供了cancel终止线程。

BlockingQueue:阻塞队列。

下面我写一个简单的事例程序:

FutureProxy.java
  1. package org.test.concurrent;   
  2. /** *//**  
  3. * <p>Title: LoonFramework</p>  
  4. * <p>Description:利用Future模式进行处理</p>  
  5. * <p>Copyright: Copyright (c) 2007</p>  
  6. * <p>Company: LoonFramework</p>  
  7. * @author chenpeng    
  8. * @email:ceponline@yahoo.com.cn   
  9. * @version 0.1  
  10. */  
  11. import java.lang.reflect.InvocationHandler;   
  12. import java.lang.reflect.Method;   
  13. import java.lang.reflect.Proxy;   
  14. import java.util.concurrent.Callable;   
  15. import java.util.concurrent.ExecutorService;   
  16. import java.util.concurrent.Executors;   
  17. import java.util.concurrent.Future;   
  18. import java.util.concurrent.ThreadFactory;   
  19.   
  20. public abstract class FutureProxy<T> {   
  21.   
  22.     private final class CallableImpl implements Callable<T> {   
  23.   
  24.         public T call() throws Exception {   
  25.             return FutureProxy.this.createInstance();   
  26.         }   
  27.     }   
  28.   
  29.     private static class InvocationHandlerImpl<T> implements InvocationHandler {   
  30.   
  31.         private Future<T> future;   
  32.            
  33.         private volatile T instance;   
  34.            
  35.         InvocationHandlerImpl(Future<T> future){   
  36.             this.future = future;   
  37.         }   
  38.            
  39.         public Object invoke(Object proxy, Method method, Object[] args)   
  40.                 throws Throwable {   
  41.             synchronized(this){   
  42.                 if(this.future.isDone()){   
  43.                     this.instance = this.future.get();   
  44.                 }else{   
  45.                     while(!this.future.isDone()){   
  46.                         try{   
  47.                             this.instance = this.future.get();   
  48.                         }catch(InterruptedException e){   
  49.                             Thread.currentThread().interrupt();   
  50.                         }   
  51.                     }   
  52.                 }   
  53.                    
  54.                 return method.invoke(this.instance, args);   
  55.             }   
  56.         }   
  57.     }   
  58.   
  59.     /** *//**  
  60.      * 实现java.util.concurrent.ThreadFactory接口  
  61.      * @author chenpeng  
  62.      *  
  63.      */  
  64.     private static final class ThreadFactoryImpl implements ThreadFactory {   
  65.   
  66.         public Thread newThread(Runnable r) {   
  67.             Thread thread = new Thread(r);   
  68.             thread.setDaemon(true);   
  69.             return thread;   
  70.         }   
  71.     }   
  72.   
  73.     private static ExecutorService service = Executors.newCachedThreadPool(new ThreadFactoryImpl());   
  74.   
  75.     protected abstract T createInstance();   
  76.   
  77.     protected abstract Class<? extends T> getInterface();   
  78.        
  79.     /** *//**  
  80.      * 返回代理的实例  
  81.      * @return  
  82.      */  
  83.     @SuppressWarnings("unchecked")   
  84.     public final T getProxyInstance() {   
  85.         Class<? extends T> interfaceClass = this.getInterface();   
  86.         if (interfaceClass == null || !interfaceClass.isInterface()) {   
  87.             throw new IllegalStateException();   
  88.         }   
  89.   
  90.         Callable<T> task = new CallableImpl();   
  91.   
  92.         Future<T> future = FutureProxy.service.submit(task);   
  93.   
  94.         return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),   
  95.                 new Class<?>[] { interfaceClass }, new InvocationHandlerImpl(future));   
  96.     }   
  97. }  

Test.java
  1. package org.test.concurrent;   
  2.   
  3. import java.util.Calendar;   
  4.   
  5. /** *//**  
  6. * <p>Title: LoonFramework</p>  
  7. * <p>Description:</p>  
  8. * <p>Copyright: Copyright (c) 2007</p>  
  9. * <p>Company: LoonFramework</p>  
  10. * @author chenpeng    
  11. * @email:ceponline@yahoo.com.cn   
  12. * @version 0.1  
  13. */  
  14. interface DateTest{   
  15.   
  16.     String getDate();   
  17. }   
  18.   
  19. class DateTestImpl implements DateTest{   
  20.        
  21.      private String _date=null;   
  22.         
  23.     public DateTestImpl(){   
  24.         try{   
  25.             _date+=Calendar.getInstance().getTime();   
  26.             //设定五秒延迟   
  27.             Thread.sleep(5000);   
  28.         }catch(InterruptedException e){   
  29.         }   
  30.     }   
  31.        
  32.     public String getDate() {   
  33.   
  34.         return "date "+_date;   
  35.     }   
  36. }   
  37.   
  38. class DateTestFactory extends FutureProxy<DateTest>{   
  39.   
  40.     @Override  
  41.     protected DateTest createInstance() {   
  42.         return new DateTestImpl();   
  43.     }   
  44.   
  45.     @Override  
  46.     protected Class<? extends DateTest> getInterface() {   
  47.         return DateTest.class;   
  48.     }   
  49. }   
  50.   
  51. public class Test{   
  52.   
  53.     public  static void main(String[] args) {   
  54.        
  55.         DateTestFactory factory = new DateTestFactory();   
  56.         DateTest[] dts = new DateTest[100];   
  57.         for(int i=0;i<dts.length;i++){   
  58.             dts[i]=factory.getProxyInstance();   
  59.         }   
  60.         //遍历执行   
  61.         for(DateTest dt : dts){   
  62.             System.out.println(dt.getDate());   
  63.         }   
  64.            
  65.     }   
  66. }  

    

posted @ 2009-07-17 20:06  tmrp  阅读(1268)  评论(0编辑  收藏  举报