浅谈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  
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. }  
[java]  view plain copy
  1. package org.test.<span class="hilite3">concurrent</span>;  
  2. /** *//** 
  3.  * <p>Title: LoonFramework</p> 
  4.  * <p>Description:利用<span class="hilite2">Future</span>模式进行处理</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 <span class="hilite1">java</span>.lang.reflect.InvocationHandler;  
  12. import <span class="hilite1">java</span>.lang.reflect.Method;  
  13. import <span class="hilite1">java</span>.lang.reflect.Proxy;  
  14. import <span class="hilite1">java</span>.util.<span class="hilite3">concurrent</span>.Callable;  
  15. import <span class="hilite1">java</span>.util.<span class="hilite3">concurrent</span>.ExecutorService;  
  16. import <span class="hilite1">java</span>.util.<span class="hilite3">concurrent</span>.Executors;  
  17. import <span class="hilite1">java</span>.util.<span class="hilite3">concurrent</span>.<span class="hilite2">Future</span>;  
  18. import <span class="hilite1">java</span>.util.<span class="hilite3">concurrent</span>.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 <span class="hilite2">Future</span><T> <span class="hilite2">future</span>;  
  32.           
  33.         private volatile T instance;  
  34.           
  35.         InvocationHandlerImpl(<span class="hilite2">Future</span><T> <span class="hilite2">future</span>)...{  
  36.             this.<span class="hilite2">future</span> = <span class="hilite2">future</span>;  
  37.         }  
  38.           
  39.         public Object invoke(Object proxy, Method method, Object[] args)  
  40.                 throws Throwable ...{  
  41.             synchronized(this)...{  
  42.                 if(this.<span class="hilite2">future</span>.isDone())...{  
  43.                     this.instance = this.<span class="hilite2">future</span>.get();  
  44.                 }else...{  
  45.                     while(!this.<span class="hilite2">future</span>.isDone())...{  
  46.                         try...{  
  47.                             this.instance = this.<span class="hilite2">future</span>.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.      * 实现<span class="hilite1">java</span>.util.<span class="hilite3">concurrent</span>.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.         <span class="hilite2">Future</span><T> <span class="hilite2">future</span> = FutureProxy.service.submit(task);  
  93.   
  94.         return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),  
  95.                 new Class<?>[] ...{ interfaceClass }, new InvocationHandlerImpl(<span class="hilite2">future</span>));  
  96.     }  
  97. }  


Test. java  
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. }  
[java]  view plain copy
  1. package org.test.<span class="hilite3">concurrent</span>;  
  2.   
  3. import <span class="hilite1">java</span>.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.       
  33.     public String getDate() ...{  
  34.   
  35.         return "date "+_date;  
  36.     }  
  37. }  
  38.   
  39.  class DateTestFactory extends FutureProxy<DateTest>...{  
  40.   
  41.     @Override  
  42.     protected DateTest createInstance() ...{  
  43.         return new DateTestImpl();  
  44.     }  
  45.   
  46.     @Override  
  47.     protected Class<? extends DateTest> getInterface() ...{  
  48.         return DateTest.class;  
  49.     }  
  50. }  
  51.   
  52. public class Test...{  
  53.   
  54.     public  static void main(String[] args) ...{  
  55.       
  56.         DateTestFactory factory = new DateTestFactory();  
  57.         DateTest[] dts = new DateTest[100];  
  58.         for(int i=0;i<dts.length;i++)...{  
  59.             dts[i]=factory.getProxyInstance();  
  60.         }  
  61.         //遍历执行  
  62.         for(DateTest dt : dts)...{  
  63.             System.out.println(dt.getDate());  
  64.         }  
  65.           
  66.     }  
  67. }  

原来很麻烦的并发处理,现在轻松的得以完成。 

我认为, concurrent 的优点在于: 

功能强大且标准化的类库,实现了很多 java  thread原生api很费时才能实现的功能。 

已经过测试,代码质量有保证,相交自己写代码处理thread,节约了大量的测试时间。 

性能上已经过优化,比如以前通过synchronized在并发量大的时候性能会不好,而 concurrent 大量用到了非阻塞算法,尽量少用锁减少等待时间。 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值