我們都知道,在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 查看複製到剪下板列印
- 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));
- }
- }
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 查看複製到剪下板列印
- 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:ceponline@yahoo.com.cn
- * @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());
- }
-
- }
- }