亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺談Android中線程池的管理

 更新時(shí)間:2018年01月18日 09:03:07   作者:堯沐  
本篇文章主要介紹了淺談Android中線程池的管理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

說到線程就要說說線程機(jī)制 Handler,Looper,MessageQueue 可以說是三座大山了

Handler

Handler 其實(shí)就是一個(gè)處理者,或者說一個(gè)發(fā)送者,它會(huì)把消息發(fā)送給消息隊(duì)列,也就是Looper,然后在一個(gè)無限循環(huán)隊(duì)列中進(jìn)行取出消息的操作 mMyHandler.sendMessage(mMessage); 這句話就是我耗時(shí)操作處理完了,我發(fā)送過去了! 然后在接受的地方處理!簡(jiǎn)單理解是不是很簡(jiǎn)單。

一般我們?cè)陧?xiàng)目中異步操作都是怎么做的呢?

// 這里開啟一個(gè)子線程進(jìn)行耗時(shí)操作
 new Thread() {
  @Override
  public void run() {
   .......
   Message mMessage = new Message();
   mMessage.what = 1;
   //在這里發(fā)送給消息隊(duì)列
   mMyHandler.sendMessage(mMessage);
   }
  }.start();
 /**
  * 這里就是處理的地方 通過msg.what進(jìn)行處理分辨
  */
 class MyHandler extends Handler{
  @Override
  public void handleMessage(Message msg) {
   super.handleMessage(msg);
   switch (msg.what){
   //取出對(duì)應(yīng)的消息進(jìn)行處理
    ........
   }
  }
 }

那么我們的消息隊(duì)列是在什么地方啟動(dòng)的呢?跟隨源碼看一看

# ActivityThread.main
public static void main(String[] args) {
  //省略代碼。。。。。
  
  //在這里創(chuàng)建了一個(gè)消息隊(duì)列!
  Looper.prepareMainLooper();

  ActivityThread thread = new ActivityThread();
  thread.attach(false);

  if (sMainThreadHandler == null) {
   sMainThreadHandler = thread.getHandler();
  }

  //這句我也沒有看懂 這不是一直都不會(huì)執(zhí)行的么
  if (false) {
   Looper.myLooper().setMessageLogging(new
     LogPrinter(Log.DEBUG, "ActivityThread"));
  }

  Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  //消息隊(duì)列跑起來了!
  Looper.loop();

  throw new RuntimeException("Main thread loop unexpectedly exited");
 }
public Handler(Callback callback, boolean async) {
  mLooper = Looper.myLooper();
  //注意看這里拋出的異常 如果這里mLooper==null
  if (mLooper == null) {
   throw new RuntimeException(
    "Can't create handler inside thread that has not called Looper.prepare()");
  }
  //獲取消息隊(duì)列
  mQueue = mLooper.mQueue;
  mCallback = callback;
  mAsynchronous = async;
 }

以上操作Android系統(tǒng)就獲取并且啟動(dòng)了一個(gè)消息隊(duì)列,過多的源碼這里不想去描述,免的占用很多篇幅

這里說一下面試常見的一個(gè)問題,就是在子線程中可不可以創(chuàng)建一個(gè)Handler,其實(shí)是可以的,但是誰這么用啊- -

new Thread() {
  Handler mHandler = null;
  @Override
  public void run() {
   //在這里獲取
   Looper.prepare();
   mHandler = new Handler();
   //在這里啟動(dòng)
   Looper.loop();
  }
 }.start();

多線程的創(chuàng)建

一般我們?cè)陂_發(fā)過程中要開啟一個(gè)線程都是直接

new Thread() {
   @Override
   public void run() {
    doing.....
   }
  }.start();
new Thread(new Runnable() {
   @Override
   public void run() {
    doing.....
   }
  }).start();

注意看,一個(gè)傳遞了Runnable對(duì)象,另一個(gè)沒有,但是這兩個(gè)有什么不同,為什么要衍生出2個(gè)呢?

這里不去看源碼,簡(jiǎn)單敘述一下,實(shí)際上Thread是 Runnabled的一個(gè)包裝實(shí)現(xiàn)類 ,Runnable只有一個(gè)方法,就 是run() ,在這里以前也想過,為什么Runnable只有一個(gè)方法呢,后來的某一次交談中也算是找到一個(gè)答案,可能是因?yàn)槎嗤卣?,可能JAVA語言想拓展一些其他的東西,以后就直接在Runnable再寫了。不然我是沒有想到另一答案為什么都要傳遞一個(gè)Runnable,可能就像我們開發(fā)中的baseActivity一樣吧

線程常用的操作方法

  1. wait() 當(dāng)一個(gè)線程執(zhí)行到了wait() 就會(huì)進(jìn)去一個(gè)和對(duì)象有關(guān)的等待池中,同時(shí)失去了釋放當(dāng)前對(duì)象的機(jī)所,使其他線程可以訪問,也就是讓其他線程可以調(diào)用notify()喚醒
  2. sleep() 調(diào)用得線程進(jìn)入睡眠狀態(tài),不能該改變對(duì)象的機(jī)鎖,其他線程不能訪問
  3. join() 就等自己完事
  4. yidld 你急你先來

簡(jiǎn)單的白話敘述其實(shí)也就是這樣,希望能看看demo然后理解一下。

一些其他的方法,Callable,Future,FutureTask

Runnable是線程管理的拓展接口,不可以運(yùn)用于線程池,所以你總要有方法可以在線程池中管理啊所以Callable,Future,FutureTask就是可以在線程池中開啟線程的接口。

Future定義了規(guī)范的接口,如get(),isDone(),isCancelled()... FutureTask 是他的實(shí)現(xiàn)類這里簡(jiǎn)單說一下他的用法

/**
 * ================================================
 * 作 者:夏沐堯 Github地址:https://github.com/XiaMuYaoDQX
 * 版 本:1.0
 * 創(chuàng)建日期: 2018/1/10
 * 描 述:
 * 修訂歷史:
 * ================================================
 */
class FutureDemo {
 //創(chuàng)建一個(gè)單例線程
 static ExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();

 public static void main(String[] args) throws ExecutionException, InterruptedException {
  ftureWithRunnable();
  ftureWithCallable();
  ftureTask();
 }

 /**
  * 沒有指定返回值,所以返回的是null,向線程池中提交的是Runnable
  *
  * @throws ExecutionException
  * @throws InterruptedException
  */
 private static void ftureWithRunnable() throws ExecutionException, InterruptedException {
  Future<?> result1 = mExecutor.submit(new Runnable() {
   @Override
   public void run() {
    fibc(20);
    System.out.println(Thread.currentThread().getName());
   }
  });
  System.out.println("Runnable" + result1.get());
 }

 /**
  * 提交了Callable,有返回值,可以獲取阻塞線程獲取到數(shù)值
  *
  * @throws ExecutionException
  * @throws InterruptedException
  */
 private static void ftureWithCallable() throws ExecutionException, InterruptedException {
  Future<Integer> result2 = mExecutor.submit(new Callable<Integer>() {
   @Override
   public Integer call() throws Exception {
    System.out.println(Thread.currentThread().getName());
    return fibc(20);
   }
  });
  System.out.println("Callable" + result2.get());
 }

 /**
  * 提交的futureTask對(duì)象
  * @throws ExecutionException
  * @throws InterruptedException
  */
 private static void ftureTask() throws ExecutionException, InterruptedException {
  FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
   @Override
   public Integer call() throws Exception {
    System.out.println(Thread.currentThread().getName());
    return fibc(20);
   }
  });
  mExecutor.submit(futureTask);
  System.out.println("futureTask" + futureTask.get());

 }

 private static int fibc(int num) {
  if (num == 0) {
   return 0;
  }
  if (num == 1) {
   return 1;
  }
  return fibc(num - 1) + fibc(num - 2);
 }
}

線程池

Java通過Executors提供線程池,分別為:

  1. newCachedThreadPool創(chuàng)建一個(gè)可緩存線程池,如果線程池長(zhǎng)度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。
  2. newFixedThreadPool 創(chuàng)建一個(gè)定長(zhǎng)線程池,可控制線程最大并發(fā)數(shù),超出的線程會(huì)在隊(duì)列中等待。
  3. newScheduledThreadPool 創(chuàng)建一個(gè)定長(zhǎng)線程池,支持定時(shí)及周期性任務(wù)執(zhí)行。
  4. newSingleThreadExecutor 創(chuàng)建一個(gè)單線程化的線程池,它只會(huì)用唯一的工作線程來執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級(jí))執(zhí)行。

示例代碼

newCachedThreadPool

創(chuàng)建一個(gè)可緩存線程池,如果線程池長(zhǎng)度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。示例代碼如下:

public class ThreadPoolExecutorTest { 
 public static void main(String[] args) { 
 ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 
 for (int i = 0; i < 10; i++) { 
 final int index = i; 
 try { 
 Thread.sleep(index * 1000); 
 } catch (InterruptedException e) { 
 e.printStackTrace(); 
 } 
 cachedThreadPool.execute(new Runnable() { 
 public void run() { 
  System.out.println(index); 
 } 
 }); 
 } 
 } 
} 

線程池為無限大,當(dāng)執(zhí)行第二個(gè)任務(wù)時(shí)第一個(gè)任務(wù)已經(jīng)完成,會(huì)復(fù)用執(zhí)行第一個(gè)任務(wù)的線程,而不用每次新建線程。

newFixedThreadPool

創(chuàng)建一個(gè)定長(zhǎng)線程池,可控制線程最大并發(fā)數(shù),超出的線程會(huì)在隊(duì)列中等待。示例代碼如下:

public class ThreadPoolExecutorTest { 
 public static void main(String[] args) { 
 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); 
 for (int i = 0; i < 10; i++) { 
 final int index = i; 
 fixedThreadPool.execute(new Runnable() { 
 public void run() { 
  try { 
  System.out.println(index); 
  Thread.sleep(2000); 
  } catch (InterruptedException e) { 
  e.printStackTrace(); 
  } 
 } 
 }); 
 } 
 } 
} 

因?yàn)榫€程池大小為3,每個(gè)任務(wù)輸出index后sleep 2秒,所以每?jī)擅氪蛴?個(gè)數(shù)字。

定長(zhǎng)線程池的大小最好根據(jù)系統(tǒng)資源進(jìn)行設(shè)置。如Runtime.getRuntime().availableProcessors()

newScheduledThreadPool

創(chuàng)建一個(gè)定長(zhǎng)線程池,支持定時(shí)及周期性任務(wù)執(zhí)行。延遲執(zhí)行示例代碼如下:

public class ThreadPoolExecutorTest { 
 public static void main(String[] args) { 
 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); 
 scheduledThreadPool.schedule(new Runnable() { 
 public void run() { 
 System.out.println("delay 3 seconds"); 
 } 
 }, 3, TimeUnit.SECONDS); 
 } 
} 

表示延遲3秒執(zhí)行。

定期執(zhí)行示例代碼如下:

public class ThreadPoolExecutorTest { 
 public static void main(String[] args) { 
 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); 
 scheduledThreadPool.scheduleAtFixedRate(new Runnable() { 
 public void run() { 
 System.out.println("delay 1 seconds, and excute every 3 seconds"); 
 } 
 }, 1, 3, TimeUnit.SECONDS); 
 } 
} 

表示延遲1秒后每3秒執(zhí)行一次。

newSingleThreadExecutor

public class ThreadPoolExecutorTest { 
 public static void main(String[] args) { 
 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); 
 for (int i = 0; i < 10; i++) { 
 final int index = i; 
 singleThreadExecutor.execute(new Runnable() { 
 public void run() { 
  try { 
  System.out.println(index); 
  Thread.sleep(2000); 
  } catch (InterruptedException e) { 
  e.printStackTrace(); 
  } 
 } 
 }); 
 } 
 } 
}

這里只是簡(jiǎn)單敘述了一下線程的管理的各種方法,后續(xù)還會(huì)針對(duì) 鎖 進(jìn)行講解

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論