//创建一个固定数量的线程池
ExecutorService es = Executors.newFixedThreadPool(3);
MyRunnable myRunnable = new MyRunnable();
//提交任务
es.submit(myRunnable);
es.submit(myRunnable);
es.submit(myRunnable);
es.submit(myRunnable);
es.submit(myRunnable);
es.submit(myRunnable);
es.submit(myRunnable);
Future<String> f = es.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "hello";
}
});
public class ThreadPool {
public static ThreadPoolExecutor pool;
static {
pool = new ThreadPoolExecutor(20, 40, 2,TimeUnit.MINUTES, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.DiscardPolicy());
}
}
static void extraFold(TextArea textArea) {
Extra.wordMeaningless.clear();
Extra.wordMeaningful.clear();
java.io.File fold = MyFile.selectFold();
textArea.append("Extra fold : " + fold.toString() + "\n");
//调用 多线程递归方法。
//初始化线程池
ListDirRunable.count = 0;
ListDirRunable.action = file -> { //处理每一个文件的方法
if (filter(file.getName())) {
Extra.extra(readFile(file));
System.out.println(ThreadPool.pool.getQueue().size() + " " + file.getName());
}
return null;
};
ThreadPool.pool.submit(new ListDirRunable(fold)); //创建提交任务
//TODO:开新线程监视
while (true) //死循环监视是否结束,目前还有问题
if (ThreadPool.pool.getQueue().size() <= 0 && ThreadPool.pool.getActiveCount() == 0 && ThreadPool.pool.getCompletedTaskCount() >= 1) {
extraFoldEnd(textArea);
textArea.append("有意义的:" + Extra.wordMeaningless.toString() + "\n");
textArea.append("无意义的:" + Extra.wordMeaningful.toString() + "\n");
System.out.println("完成");
break;
}
}
public class ListDirRunable implements Runnable {
public static FileAction action;
public static int count = 0;
public static ReentrantLock lock = new ReentrantLock();
private File dir;
public ListDirRunable(File dir) {
this.dir = dir;
}
@Override
public void run() {
if (!dir.exists())
throw new IllegalArgumentException("目录:" + dir + "不存在.");
if (!dir.isDirectory()) {
throw new IllegalArgumentException(dir + "不是目录。");
}
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isDirectory())
ThreadPool.pool.submit(new ListDirRunable(file));
else if (file.isFile()) {
try {
action.main(file); //调用对文件的操作
lock.lock();
count++;
} finally {
lock.unlock();
}
//System.out.println("\nfileCount = " + count);
}
}
}
}
}
class PausableThreadPoolExecutor extends ThreadPoolExecutor {
private boolean isPaused;
private ReentrantLock pauseLock = new ReentrantLock();
private Condition unpaused = pauseLock.newCondition();
public PausableThreadPoolExecutor(...) { super(...); }
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
pauseLock.lock();
try {
while (isPaused) unpaused.await();
} catch(InterruptedException ie) {
t.interrupt();
} finally {
pauseLock.unlock();
}
}
public void pause() {
pauseLock.lock();
try finally {
pauseLock.unlock();
}
}
public void resume() {
pauseLock.lock();
try {
isPaused = false;
unpaused.signalAll();
} finally {
pauseLock.unlock();
}
}
}
评论区