走進Java Android 的執行緒世界(一)

Tongson發表於2018-12-04

直奔主題

首先我們來看看Java的執行緒通訊基礎


    //產品
    static class ProductObject{
        //執行緒操作變數可見
        public volatile static String value;
    }

    //生產者執行緒
    static class Producer extends Thread{
        Object lock;

        public Producer(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            //不斷生產產品
            while(true){
                synchronized (lock) { //互斥鎖
                    //產品還沒有被消費,等待
                    if(ProductObject.value != null){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //產品已經消費完成,生產新的產品
                    ProductObject.value = "NO:"+System.currentTimeMillis();
                    Log.i(TAG,"生產產品:"+ProductObject.value);
                    lock.notify(); //生產完成,通知消費者消費
                }
            }

        }
    }

    //消費者執行緒
    static class Consumer extends Thread{
        Object lock;
        public Consumer(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            while(true){
                synchronized (lock) {
                    //沒有產品可以消費
                    if(ProductObject.value == null){
                        //等待,阻塞
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.i(TAG,"消費產品:"+ProductObject.value);
                    ProductObject.value = null;
                    lock.notify(); //消費完成,通知生產者,繼續生產
                }
            }
        }
    }
複製程式碼

呼叫:

        Object lock = new Object();
        new Producer(lock).start();
        new Consumer(lock).start();
複製程式碼

Log:

這裡寫圖片描述

這是一些簡單的執行緒通訊基礎,兩個執行緒進行互動的用法。

接下來分析一下 Java中的FutureTask

我們先來看看類圖

這裡寫圖片描述
再看看怎麼用的

    //非同步任務
    static class Task implements Callable<Integer> {
        //返回非同步任務的執行結果
        @Override
        public Integer call() throws Exception {
            int i = 0;
            for (; i < 10; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, Thread.currentThread().getName() + "_" + i);
            }
            return i;
        }
    }
複製程式碼

初始化執行

        Task work = new Task();
        FutureTask<Integer> future = new FutureTask<Integer>(work) {
            //非同步任務執行完成,回撥
            @Override
            protected void done() {
                try {
                    Log.i(TAG, "done:" + get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        };
        //執行緒池(使用了預定義的配置)
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(future);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        //取消非同步任務
//        future.cancel(true);
        try {
            //阻塞,等待非同步任務執行完畢
            Log.i(TAG, "" + future.get());

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
複製程式碼

Log:

這裡寫圖片描述
從上面程式碼可以看出 這個FutureTask 解決非同步任務執行的結果,主執行緒無法輕易的獲取 這是怎麼做到的呢-->我們就需要翻越FutureTask的程式碼

Future

package java.util.concurrent;

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
複製程式碼

Runnable

package java.lang;

public interface Runnable {
    public abstract void run();
}
複製程式碼

RunnableFuture

package java.util.concurrent;

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}
複製程式碼

FutureTask


package java.util.concurrent;

import java.util.concurrent.locks.LockSupport;

public class FutureTask<V> implements RunnableFuture<V> {
	......以下只擷取部分程式碼
    /** The underlying callable; nulled out after running */
    private Callable<V> callable;

    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              U.compareAndSwapInt(this, STATE, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    U.putOrderedInt(this, STATE, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

    /**
     * @throws CancellationException {@inheritDoc}
     */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }



    
    protected void done() { }

   
    protected void set(V v) {
        if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
            outcome = v;
            U.putOrderedInt(this, STATE, NORMAL); // final state
            finishCompletion();
        }
    }

    
    protected void setException(Throwable t) {
        if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
            outcome = t;
            U.putOrderedInt(this, STATE, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

    public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

   
    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (U.compareAndSwapObject(this, WAITERS, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }
    ......以上只擷取部分程式碼
}
複製程式碼

從上面程式碼可以看出

Java FutureTask 非同步任務操作提供了便利性

1.獲取非同步任務的返回值--> V get()

2.監聽非同步任務的執行完畢-->finishCompletion()-->done()

3.取消非同步任務-->cancel(boolean mayInterruptIfRunning)

從上面的例子,我們可以看到Executors去呼叫這個Future那麼這個Executors又是啥玩意呢?!

像剛才看Future那樣我們點進去看看這個Executors我們可以發現很多東西,然而,其實這個就是鼎鼎大名的 執行緒池 ! 我們還是先看看類圖

這裡寫圖片描述

因為實現類方法太多了,還是直接看api文件比較好。

一個任務

    static class MyTask implements Runnable {

        int i;

        public MyTask(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            Log.i(TAG, Thread.currentThread().getName() + ";i:" + i);
        }
        
    }
複製程式碼

初始化-->執行執行緒池

        int CPU_COUNT = Runtime.getRuntime().availableProcessors();  //可用的CPU個數
        Log.i(TAG, "CPU_COUNT-->" + CPU_COUNT);
        int CORE_POOL_SIZE = CPU_COUNT + 1; //5(corePoolSize - 池中所儲存的執行緒數,包括空閒執行緒。)
        Log.i(TAG, "CORE_POOL_SIZE-->" + CORE_POOL_SIZE);
        int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; //9(maximumPoolSize - 池中允許的最大執行緒數。)
        Log.i(TAG, "MAXIMUM_POOL_SIZE-->" + MAXIMUM_POOL_SIZE);

        int KEEP_ALIVE = 1;//(keepAliveTime - 當執行緒數大於核心時,此為終止前多餘的空閒執行緒等待新任務的最長時間。)

        //任務佇列(128)(workQueue - 執行前用於保持任務的佇列。此佇列僅由保持 execute 方法提交的 Runnable 任務。)
        final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128);

        //執行緒工廠(threadFactory - 執行程式建立新執行緒時使用的工廠。)
        ThreadFactory sThreadFactory = new ThreadFactory() {
            private final AtomicInteger mCount = new AtomicInteger(1);

            public Thread newThread(Runnable r) {
                String name = "Thread #" + mCount.getAndIncrement();
                Log.i(TAG, "newThread-->" + name);
                return new Thread(r, name);
            }
        };

        //執行緒池
        Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                //(unit - keepAliveTime 引數的時間單位。)
                TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
        
        
        /*  如果執行的執行緒少於 corePoolSize,則 Executor 始終首選新增新的執行緒,而不進行排隊。
            如果執行的執行緒等於或多於 corePoolSize,則 Executor 始終首選將請求加入佇列,而不新增新的執行緒。
            如果無法將請求加入佇列,則建立新的執行緒,除非建立此執行緒超出 maximumPoolSize,在這種情況下,任務將被拒絕。*/
        //執行非同步任務
        //如果當前執行緒池中的數量大於corePoolSize,緩衝佇列workQueue已滿,
        //並且執行緒池中的數量等於maximumPoolSize,新提交任務由Handler處理。
        //RejectedExecutionException
        for (int i = 0; i < 200; i++) {
            //相當於new AsyncTask().execute();
            THREAD_POOL_EXECUTOR.execute(new MyTask(i));
        }
複製程式碼

Log如下

這裡寫圖片描述
從Log我們可以看出每個任務都有一個執行緒去完成。

其實這個就是Android中AsyncTask的原理我們不妨分析一下AsyncTask:

初始化

這裡寫圖片描述

執行

這裡寫圖片描述

返回

這裡寫圖片描述

返回UI執行緒

這裡寫圖片描述

Progress更新UI

這裡寫圖片描述

JAVA API 文件:tool.oschina.net/apidocs/api…

Android API文件:tool.oschina.net/apidocs/api…

文章程式碼:github.com/gepriniusce…

相關文章