談談java.util.concurrent包的併發處理(轉)

淺談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:[email protected]   
  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:[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
  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:[email protected]   
  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. }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章