源碼翻譯師1 Android-Lite-Go(Part3)

回歸正題,繼續(xù)看源碼

(1)構(gòu)造函數(shù)部分

public SmartExecutor() {    
    initThreadPool();
}
public SmartExecutor(int coreSize, int queueSize) {    
    this.coreSize = coreSize;    
    this.queueSize = queueSize;    
    initThreadPool();
}
protected synchronized void initThreadPool() {    
    if (threadPool == null) {       
        threadPool = createDefaultThreadPool();    
    }
}
public static ThreadPoolExecutor createDefaultThreadPool() {    
    // 控制最多4個(gè)keep在pool中    
    int corePoolSize = Math.min(4, CPU_CORE);    
    return new ThreadPoolExecutor(            
         corePoolSize,            
         Integer.MAX_VALUE,            
         DEFAULT_CACHE_SECOND, 
         TimeUnit.SECONDS,            
         new SynchronousQueue<Runnable>(),            
         new ThreadFactory() {                
                  static final String NAME = "lite-";                
                  AtomicInteger IDS = new AtomicInteger(1);                
                  @Override                
                  public Thread newThread(Runnable r) {                    
                           return new Thread(r, NAME+IDS.getAndIncrement());                
                  }            
          },            
          new ThreadPoolExecutor.DiscardPolicy());
}

需要注意的地方是initThreadPool()方法加了一個(gè)對(duì)象鎖,為了防止在不同線程同時(shí)調(diào)用該方法。但是如果在不同線程創(chuàng)建不同的SmartExecutor對(duì)象會(huì)如何呢?這個(gè)鎖豈不是就不起作用了?
再次閱讀了下關(guān)于java多線程的知識(shí),得到的解釋是:java 方法本身是線程安全的。但是有一個(gè)問題在于,在方法中有沒有全局變量(類靜態(tài)變量、對(duì)象實(shí)例變量),如果有全局變量,在多線程調(diào)用的時(shí)候要多加注意進(jìn)行同步處理。
所以個(gè)人認(rèn)為,這里使用synchronized是為了保護(hù)靜態(tài)變量threadPool。而如果在不同的線程創(chuàng)建不同的對(duì)象,是有可能發(fā)生線程不安全的。當(dāng)然,在一般的使用場(chǎng)景下,這種可能性非常小。

(2)任務(wù)封裝

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {    
    return new FutureTask<T>(runnable, value);
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {    
    return new FutureTask<T>(callable);
}

AbstractExecutorService里看到過的代碼,分別:

  • 為指定的Runnable和value構(gòu)造一個(gè)FutureTask,value表示默認(rèn)被返回的Future。
  • 為指定的Callable創(chuàng)建一個(gè)FutureTask。

(3)提交

    /*
     * 提交Runnable任務(wù)
     */
    public Future<?> submit(Runnable task) {
        // 通過newTaskFor方法構(gòu)造RunnableFuture,默認(rèn)的返回值是null
        RunnableFuture<Object> ftask = newTaskFor(task, null);
        // 調(diào)用具體實(shí)現(xiàn)的execute方法
        execute(ftask);
        return ftask;
    }
    /*
     * 提交Runnable任務(wù)
     */
    public <T> Future<T> submit(Runnable task, T result) {
        // 通過newTaskFor方法構(gòu)造RunnableFuture,默認(rèn)的返回值是result
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }
    /*
     * 提交Callable任務(wù)
     */
    public <T> Future<T> submit(Callable<T> task) {
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

同樣來自于AbstractExecutorService

(4)execute方法

@Override
public void execute(final Runnable command) {
    if (command == null) {
        return;
    }

    WrappedRunnable scheduler = new WrappedRunnable() {
        @Override
        public Runnable getRealRunnable() {
            return command;
        }

        public Runnable realRunnable;

        @Override
        public void run() {
            try {
                command.run();
            } finally {
                scheduleNext(this);
            }
        }
    };

    boolean callerRun = false;
    synchronized (lock) {
        if (runningList.size() < coreSize) {
            runningList.add(scheduler);
            threadPool.execute(scheduler);
        } else if (waitingList.size() < queueSize) {
            waitingList.addLast(scheduler);
        } else {
            switch (overloadPolicy) {
                case DiscardNewTaskInQueue:
                    waitingList.pollLast();
                    waitingList.addLast(scheduler);
                    break;
                case DiscardOldTaskInQueue:
                    waitingList.pollFirst();
                    waitingList.addLast(scheduler);
                    break;
                case CallerRuns:
                    callerRun = true;
                    break;
                case DiscardCurrentTask:
                    break;
                case ThrowExecption:
                    throw new RuntimeException("Task rejected from lite smart executor. " + command.toString());
                default:
                    break;
            }
        }
        //printThreadPoolInfo();
    }
    if (callerRun) {
        command.run();
    }
}

核心代碼。

  • 這里WrappedRunnable繼承Runnable接口,在execute里用匿名內(nèi)部類的方式生成了scheduler對(duì)象。
  • 下面進(jìn)行判斷,當(dāng)運(yùn)行鏈表未滿時(shí),加入運(yùn)行鏈表,同時(shí)執(zhí)行任務(wù);當(dāng)?shù)却湵砦礉M時(shí),加入等待鏈表;如都不滿足,則根據(jù)過載策略,來選擇處理方式。這里可以發(fā)現(xiàn),CallerRuns表示在調(diào)用的線程中執(zhí)行任務(wù),執(zhí)行后并不會(huì)進(jìn)行其他操作。
  • CallerRuns策略執(zhí)行的任務(wù)在完成后會(huì)調(diào)用scheduleNext(WrappedRunnable scheduler)方法,將scheduler從運(yùn)行隊(duì)列中remove。然后從等待隊(duì)列中根據(jù)排序策略選擇下一個(gè)執(zhí)行的任務(wù),加入運(yùn)行隊(duì)列,并執(zhí)行。
  • 所有有關(guān)全局變量的操作都加上了同步鎖,保證線程安全

OK,這篇源碼到這里就全部結(jié)束了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容