執行器(Executor)類有大量用來構建線程池的靜態工廠方法
newCachedThreadPool
向線程池提交任務的方法為
Future<?> submit(Runable task)
Future<T> submit(Runable task
Future<t> submit(Callable<T> task)
線程池會在適當的時候盡早執行提交的任務
第一個submit方法提交一個Runable對象返回一個Future<?>
第二個版本的submit方法同樣提交一個Runable對象
第三個submit方法提交一個Callable對象
當想要注銷一個線程池
下面總結了在使用連接池時應該做的事
調用Executor類中靜態的newCachedThreadPool或newFixedThreadPool方法
調用submit來提交一個Runnable或Callable對象
如果希望能夠取消任務或如果提交了一個Callable對象
當不想再提交任何任務時調用shutdown
除了常規的計算匹配文件數量外
import java
import java
import ncurrent
public class ThreadPoolTest
{
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System
System
String directory = in
System
String keyword = in
ExecutorService pool = Executors
MatchCounter counter = new MatchCounter(new File(directory)
Future<Integer> result = pool
try
{
System
}
catch (ExecutionException e)
{
e
}
catch (InterruptedException e)
{
}
pool
int largestPoolSize = ((ThreadPoolExecutor) pool)
System
} } /**
* This task counts the files in a directory and its subdirectories that contain a given keyword
*/ class MatchCounter implements Callable<Integer> {
/**
* Constructs a MatchCounter
* @param directory the directory in which to start the search
* @param keyword the keyword to look for
* @param pool the thread pool for submitting subtasks
*/
public MatchCounter(File directory
{
this
this
this
}
public Integer call()
{
count =
try
{
File[] files = directory
ArrayList<Future<Integer》 results = new ArrayList<Future<Integer》()
for (File file : files)
if (file
{
MatchCounter counter = new MatchCounter(file
Future<Integer> result = pool
results
}
else
{
if (search(file)) count++;
}
for (Future<Integer> result : results)
try
{
count += result
}
catch (ExecutionException e)
{
e
}
}
catch (InterruptedException e)
{
}
return count;
}
/**
* Searches a file for a given keyword
* @param file the file to search
* @return true if the keyword is contained in the file
*/ public boolean search(File file)
{
try
{
Scanner in = new Scanner(new FileInputStream(file))
boolean found = false;
while (!found && in
{
String line = in
if (ntains(keyword)) found = true;
}
in
return found;
}
catch (IOException e)
{
return false;
}
}
private File directory;
private String keyword;
private ExecutorService pool;
private int count;
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27555.html