淺談java.util.concurrent包的並發處理)

來源:互聯網
上載者:User
我們都知道,在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. }  
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:ceponline@yahoo.com.cn * @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 查看複製到剪下板列印

  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. }  

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.