Java代碼??
public interface Executor {??
??
? ? /**?
? ? ?* Executes the given command at some time in the future.? The command?
? ? ?* may execute in a new thread, in a pooled thread, or in the calling?
? ? ?* thread, at the discretion of the <tt>Executor</tt> implementation.?
? ? ?*?
? ? ?* @param command the runnable task?
? ? ?* @throws RejectedExecutionException if this task cannot be?
? ? ?* accepted for execution.?
? ? ?* @throws NullPointerException if command is null?
? ? ?*/??
? ? void execute(Runnable command);??
}??
?
Java代碼??
//接口ExecutorService繼承自Executor,它的目的是為我們管理Thread對象,從而簡化并發編程??
public interface ExecutorService extends Executor {??
??
? ? <T> Future<T> submit(Callable<T> task);??
? ? ?
? ? <T> Future<T> submit(Runnable task, T result);??
??
? ? Future<?> submit(Runnable task);??
? ? ??
? ? ...? ? ?
}??
?
Java代碼??
public interface Callable<V> {??
? ? /**?
? ? ?* Computes a result, or throws an exception if unable to do so.?
? ? ?*?
? ? ?* @return computed result?
? ? ?* @throws Exception if unable to compute a result?
? ? ?*/??
? ? V call() throws Exception;??
}??
??
??
public interface Runnable {??
? ? ?
? ? public abstract void run();??
}??
?
Java代碼??
public interface Future<V> {??
? ? ??
? ? boolean cancel(boolean mayInterruptIfRunning);? ? ??
??
? ? /**?
? ? ?* Waits if necessary for the computation to complete, and then?
? ? ?* retrieves its result.?
? ? ?*?
? ? ?* @return the computed result? ?
? ? ?*/??
? ? V get() throws InterruptedException, ExecutionException;??
??
? ? ?
? ? V get(long timeout, TimeUnit unit)??
? ? ? ? throws InterruptedException, ExecutionException, TimeoutException;??
}??
?
Callable接口和Runnable接口相似,區別就是Callable需要實現call方法,而Runnable需要實現run方法;并且,call方法還可以返回任何對象,無論是什么對象,JVM都會當作Object來處理。但是如果使用了泛型,我們就不用每次都對Object進行轉換了。
?
Runnable和Callable都是接口
不同之處:
1.Callable可以返回一個類型V,而Runnable不可以
2.Callable能夠拋出checked exception,而Runnable不可以。
3.Runnable是自從java1.1就有了,而Callable是1.5之后才加上去的
4.Callable和Runnable都可以應用于executors。而Thread類只支持Runnable.
上面只是簡單的不同,其實這兩個接口在用起來差別還是很大的。Callable與executors聯合在一起,在任務完成時可立刻獲得一個更新了的Future。而Runable卻要自己處理
?
? Future接口,一般都是取回Callable執行的狀態用的。其中的主要方法:
cancel,取消Callable的執行,當Callable還沒有完成時
get,獲得Callable的返回值
isCanceled,判斷是否取消了
isDone,判斷是否完成
?
用Executor來構建線程池,應該要做的事:
1).調用Executors類中的靜態方法newCachedThreadPool(必要時創建新線程,空閑線程會被保留60秒)或newFixedThreadPool(包含固定數量的線程池)等,返回的是一個實現了ExecutorService接口的ThreadPoolExecutor類或者是一個實現了ScheduledExecutorServiece接口的類對象。
2).調用submit提交Runnable或Callable對象。
3).如果想要取消一個任務,或如果提交Callable對象,那就要保存好返回的Future對象。
4).當不再提交任何任務時,調用shutdown方法。
?
舉2個例子如下:
Java代碼? ?
package thread.test04;??
import java.util.concurrent.*;??
public class ThreadTestA {??
? ? public static void main(String[] args) {??
? ? ? ? ExecutorService e=Executors.newFixedThreadPool(10);??
? ? ? ? e.execute(new MyRunnableA());??
? ? ? ? e.execute(new MyRunnableB());??
? ? ? ?e.shutdown();??
? ?}??
??
}??
??
class MyRunnableA implements Runnable{??
? ? ??
? ? public void run(){??
? ? ? ? System.out.println("Runnable:run()....");??
? ? ? ? int i=0;??
? ? ? ? while(i<20){??
? ? ? ? ? ? i++;??
? ? ? ? ? ? for(int j=0;j<1000000;j++);??
? ? ? ? ? ? System.out.println("i="+i);??
? ? ? ? }??
? ? }??
}??
??
class MyRunnableB implements Runnable{??
? ? public void run(){??
? ? ? ? char c='A'-1;??
? ? ? ? while(c<'Z'){??
? ? ? ? ? ? c++;??
? ? ? ? ? ? for(int j=0;j<1000000;j++);??
? ? ? ? ? ? System.out.println("c="+c);??
? ? ? ? }??
? ? }??
}??
?
Java代碼? ?
package thread.test04;??
??
import java.util.concurrent.Callable;??
import java.util.concurrent.ExecutionException;??
import java.util.concurrent.ExecutorService;??
import java.util.concurrent.Executors;??
import java.util.concurrent.Future;??
??
public class ThreadTestB {??
? ? public static void main(String[] args) {??
? ? ? ? ExecutorService e=Executors.newFixedThreadPool(10);??
? ? ? ? Future f1=e.submit(new MyCallableA());??
? ? ? ? Future f2=e.submit(new MyCallableA());??
? ? ? ? Future f3=e.submit(new MyCallableA());? ? ? ??
? ? ? ? System.out.println("--Future.get()....");??
? ? ? ? try {??
? ? ? ? ? ? System.out.println(f1.get());??
? ? ? ? ? ? System.out.println(f2.get());??
? ? ? ? ? ? System.out.println(f3.get());? ? ? ? ? ??
? ? ? ? } catch (InterruptedException e1) {??
? ? ? ? ? ? e1.printStackTrace();??
? ? ? ? } catch (ExecutionException e1) {??
? ? ? ? ? ? e1.printStackTrace();??
? ? ? ? }??
? ? ? ? ??
? ? ? ? e.shutdown();??
? ? ? ? ??
? ? }??
??
}??
??
class MyCallableA implements Callable<String>{??
? ? public String call() throws Exception {??
? ? ? ? System.out.println("開始執行Callable");??
? ? ? ? String[] ss={"zhangsan","lisi"};??
? ? ? ? long[] num=new long[2];??
? ? ? ? for(int i=0;i<1000000;i++){??
? ? ? ? ? ? num[(int)(Math.random()*2)]++;??
? ? ? ? }??
? ? ? ? ??
? ? ? ? if(num[0]>num[1]){??
? ? ? ? ? ? return ss[0];??
? ? ? ? }else if(num[0]<num[1]){??
? ? ? ? ? ? throw new Exception("棄權!");??
? ? ? ? }else{??
? ? ? ? ? ? return ss[1];??
? ? ? ? }??
? ? }??
? ? ??
}??
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。