自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

基于線程池的匹配文件數(shù)量計算

開發(fā) 后端
構(gòu)建一個新的線程的代價還是有些高的,因為它涉及與操作系統(tǒng)的交互。如果你的程序創(chuàng)建了大量生存期很短的線程,那就應該使用線程池。一個線程池包含大量準備運行的空閑線程。你將一個Runnable對象給線程池,線程池中的一個線程就會調(diào)用run方法。當run方法退出時,線程不會死亡,而是繼續(xù)在池中準備為下一個請求提供服務。

構(gòu)建一個新的線程的代價還是有些高的,因為它涉及與操作系統(tǒng)的交互。如果你的程序創(chuàng)建了大量生存期很短的線程,那就應該使用線程池。一個線程池包含大量準備運行的空閑線程。你將一個Runnable對象給線程池,線程池中的一個線程就會調(diào)用run方法。當run方法退出時,線程不會死亡,而是繼續(xù)在池中準備為下一個請求提供服務。

執(zhí)行器(Executor)類有大量用來構(gòu)建線程池的靜態(tài)工廠方法,下表給出了一個總結(jié)。

 方法 描述 
 newCachedThreadPool 在需要時創(chuàng)建新線程:空閑線程會被保留60秒 
 newFixedThreadPool  池包含固定數(shù)量的線程;空閑線程會一直被保留
 newSingleThreadExecutor  只有一個線程的“池”,這個線程順序執(zhí)行每一個遞交上來的任務
 newScheduledThreadPool  為預定執(zhí)行而構(gòu)建的固定線程池
 newSingleThreadScheduledExecutor  為預定執(zhí)行而構(gòu)建的單線程“池”

newCachedThreadPool、newFixedThreadPool和newSingleThreadExecutor這三個方法返回ThreadPoolExecutor類(這個類實現(xiàn)了ExecutorService接口)對象。

向線程池提交任務的方法為:將一個實現(xiàn)Runnable或Callable接口的對象提交給ExecutorService:

  1. Future<?> submit(Runable task)  
  2.  
  3. Future<T> submit(Runable task, T result)  
  4.  
  5. Future<t> submit(Callable<T> task) 

線程池會在適當?shù)臅r候盡早執(zhí)行提交的任務,調(diào)用submit時會返回一個Future對象,用以查詢該任務的狀態(tài),或者取消該任務。

***個submit方法提交一個Runable對象返回一個Future<?>,可使用該對象調(diào)用isDone、cancel、或者isCancelled來查詢?nèi)蝿諣顟B(tài)。但是此Future對象的get方法在任務完成的時候知識簡單的返回null;

第二個版本的submit方法同樣提交一個Runable對象,并且返回Future的get方法在任務完成的時候返回傳入的result對象;

第三個submit方法提交一個Callable對象,并且返回的Future對象將在計算結(jié)構(gòu)、準備好的時候得到它。

當想要注銷一個線程池,可調(diào)用shutdown方法,該方法啟動該線程池的關閉序列。此時線程池并不是馬上就壯烈犧牲了線程也沒了,而是等待所以任務都完成以后,線程池中的線程才會死亡,被關閉的執(zhí)行器不再接受新任務。也可以調(diào)用shutdownNow,此時線程池會取消正在排隊等待處理的任務并且試圖中斷正在執(zhí)行的線程。

下面總結(jié)了在使用連接池時應該做的事:

  1. 調(diào)用Executor類中靜態(tài)的newCachedThreadPool或newFixedThreadPool方法。
  2. 調(diào)用submit來提交一個Runnable或Callable對象。
  3. 如果希望能夠取消任務或如果提交了一個Callable對象,那就保存好返回的Future對象。
  4. 當不想再提交任何任務時調(diào)用shutdown。

除了常規(guī)的計算匹配文件數(shù)量外,這個程序打印出執(zhí)行過程中池中的***線程數(shù)量。但從ExecutorService接口不能得到這個信息。因此,我們必須將pool對象轉(zhuǎn)型成一個ThreadPoolExecutor類對象。

  1. import java.io.*;  
  2. import java.util.*;  
  3. import java.util.concurrent.*;  
  4.  
  5. public class ThreadPoolTest  
  6. {  
  7.    public static void main(String[] args) throws Exception  
  8.    {  
  9.       Scanner in = new Scanner(System.in);  
  10.       System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");  
  11.       String directory = in.nextLine();  
  12.       System.out.print("Enter keyword (e.g. volatile): ");  
  13.       String keyword = in.nextLine();  
  14.  
  15.       ExecutorService pool = Executors.newCachedThreadPool();  
  16.  
  17.       MatchCounter counter = new MatchCounter(new File(directory), keyword, pool);  
  18.       Future<Integer> result = pool.submit(counter);  
  19.  
  20.       try 
  21.       {  
  22.          System.out.println(result.get() + " matching files.");  
  23.       }  
  24.       catch (ExecutionException e)  
  25.       {  
  26.          e.printStackTrace();  
  27.       }  
  28.       catch (InterruptedException e)  
  29.       {  
  30.       }  
  31.       pool.shutdown();  
  32.  
  33.       int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();  
  34.       System.out.println("largest pool size=" + largestPoolSize);  
  35.    }  
  36. }  
  37.  
  38. /**  
  39.  * This task counts the files in a directory and its subdirectories that contain a given keyword.  
  40.  */ 
  41. class MatchCounter implements Callable<Integer>  
  42. {  
  43.    /**  
  44.     * Constructs a MatchCounter.  
  45.     * @param directory the directory in which to start the search  
  46.     * @param keyword the keyword to look for  
  47.     * @param pool the thread pool for submitting subtasks  
  48.     */ 
  49.    public MatchCounter(File directory, String keyword, ExecutorService pool)  
  50.    {  
  51.       this.directory = directory;  
  52.       this.keyword = keyword;  
  53.       this.pool = pool;  
  54.    }  
  55.  
  56.    public Integer call()  
  57.    {  
  58.       count = 0;  
  59.       try 
  60.       {  
  61.          File[] files = directory.listFiles();  
  62.          ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();  
  63.  
  64.          for (File file : files)  
  65.             if (file.isDirectory())  
  66.             {  
  67.                MatchCounter counter = new MatchCounter(file, keyword, pool);  
  68.                Future<Integer> result = pool.submit(counter);  
  69.                results.add(result);  
  70.             }  
  71.             else 
  72.             {  
  73.                if (search(file)) count++;  
  74.             }  
  75.  
  76.          for (Future<Integer> result : results)  
  77.             try 
  78.             {  
  79.                count += result.get();  
  80.             }  
  81.             catch (ExecutionException e)  
  82.             {  
  83.                e.printStackTrace();  
  84.             }  
  85.       }  
  86.       catch (InterruptedException e)  
  87.       {  
  88.       }  
  89.       return count;  
  90.    }  
  91.  
  92.    /**  
  93.     * Searches a file for a given keyword.  
  94.     * @param file the file to search  
  95.     * @return true if the keyword is contained in the file  
  96.     */ 
  97.    public boolean search(File file)  
  98.    {  
  99.       try 
  100.       {  
  101.          Scanner in = new Scanner(new FileInputStream(file));  
  102.          boolean found = false;  
  103.          while (!found && in.hasNextLine())  
  104.          {  
  105.             String line = in.nextLine();  
  106.             if (line.contains(keyword)) found = true;  
  107.          }  
  108.          in.close();  
  109.          return found;  
  110.       }  
  111.       catch (IOException e)  
  112.       {  
  113.          return false;  
  114.       }  
  115.    }  
  116.  
  117.    private File directory;  
  118.    private String keyword;  
  119.    private ExecutorService pool;  
  120.    private int count;  

原文鏈接:http://www.cnblogs.com/XL-Liang/archive/2012/06/13/2548327.html

責任編輯:林師授 來源: frogong的博客
相關推薦

2015-07-22 18:07:59

阿里云批量計算

2017-11-27 08:38:10

UPS選擇容量

2018-08-15 09:13:27

布線系統(tǒng)線纜用量

2009-08-21 10:50:42

電線電纜材料用量

2024-01-16 10:45:31

C++語言代碼

2021-03-01 15:55:17

Go惡意軟件勒索軟件

2015-05-04 14:46:49

2017-01-06 11:18:58

星瑞格

2018-02-28 16:20:57

中科睿芯

2019-06-06 10:19:33

谷歌開源計算庫

2010-12-23 09:46:03

UNIXSSH

2018-01-24 09:27:30

文本分類工具fastText

2024-03-04 09:55:11

開源模型訓練

2016-12-06 15:40:08

海量計算星瑞格

2021-09-23 15:55:50

線程池語言公式

2021-04-01 13:05:55

無文件惡意軟件威脅情報攻擊

2012-07-16 13:17:02

Android惡意軟件惡意軟件
點贊
收藏

51CTO技術(shù)棧公眾號