Java線程池相關類-Executor架構

來源:互聯網
上載者:User

標籤:ack   ***   pointer   get   nbsp   getname   submit   異常   interrupt   

1.Executor

介面源碼:

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);}

介面使用:

public class T01_MyExecutor implements Executor {    public static void main(String[] args) {        new T01_MyExecutor().execute(()->System.out.println("hello executor"));    }    @Override    public void execute(Runnable command) {        //new Thread(command).run();        command.run();    }}

2.ExecutorService

源碼:

認識submit方法,擴充了execute方法,具有一個傳回值

<T> Future<T> submit(Callable<T> task);<T> Future<T> submit(Runnable task, T result);Future<?> submit(Runnable task);

使用:

ExecutorService提供了管理Eecutor生命週期的方法,ExecutorService的生命週期包括了:運行  關閉和終止三種狀態。 ExecutorService在初始化建立時處於運行狀態。shutdown方法等待提交的任務執行完成並不再接受新任務,在完成全部提交的任務後關閉shutdownNow方法將強制終止所有運行中的任務並不再允許提交新任務 可以將一個Runnable或Callable提交給ExecutorService的submit方法執行,最終返回一上Futire用來獲得任務的執行結果或取消任務(任務執行完成後並返回執行結果)
public class CallableAndFuture {    public static void main(String[] args) throws ExecutionException, InterruptedException {        ExecutorService executor = Executors.newSingleThreadExecutor();        Future<String> future = executor.submit(new Callable<String>() {   //接受一上callable執行個體            public String call() throws Exception {                return "MOBIN";            }        });        System.out.println("任務的執行結果:"+future.get());    }}
輸出:
任務的執行結果:MOBIN

3.Executors

提供了一系列靜態Factory 方法用於建立各種線程池

   newFixedThreadPool:建立可重用且固定線程數的線程池,如果線程池中的所有線程都處於活動狀態,此時再提交任務就在隊列中等待,直到有可用線程;如果線程池中的某個線程由於異常而結束時,線程池就會再補充一條新線程。
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

4.ThreadPool

線程池的概念

public static void main(String[] args) throws InterruptedException {        ExecutorService service = Executors.newFixedThreadPool(5); //execute submit        for (int i = 0; i < 6; i++) {            service.execute(() -> {                try {                    TimeUnit.MILLISECONDS.sleep(500);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println(Thread.currentThread().getName());            });        }        System.out.println(service);                service.shutdown();        System.out.println(service.isTerminated());        System.out.println(service.isShutdown());        System.out.println(service);                TimeUnit.SECONDS.sleep(5);        System.out.println(service.isTerminated());        System.out.println(service.isShutdown());        System.out.println(service);    }

5.Future

public static void main(String[] args) throws InterruptedException, ExecutionException {                FutureTask<Integer> task = new FutureTask<>(()->{            TimeUnit.MILLISECONDS.sleep(500);            return 1000;        }); //new Callable () { Integer call();}                new Thread(task).start();                System.out.println(task.get()); //阻塞                //*******************************        ExecutorService service = Executors.newFixedThreadPool(5);        Future<Integer> f = service.submit(()->{            TimeUnit.MILLISECONDS.sleep(500);            return 1;        });        System.out.println(f.get());        System.out.println(f.isDone());            }

6.

Java線程池相關類-Executor架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.