线程池如果不关闭,则主线程无法终止,因为线程池中的核心线程永远不会被回收,除非关闭线程池,或者应用程序终止。
ThreadFactory中可以将线程设置为守护线程,主线程可以正常执行并结束退出,但是主线程运行结束子线程还没有运行结束。所以还是需要关闭线程池。等线程池中的任务都运行完之后再执行主线程的内容。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Author: 17976
* Date: 2021/7/13 20:53
* Description:
*/
public class ReadLineTest {
public static void main(String[] args){
//源文件地址
String sourcePath = "F:\\IdeaWork\\userAuditStatusRecord.txt";
//目标文件地址
String destnationPath = "F:\\IdeaWork\\errorRecord.txt";
File file = new File(sourcePath);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line = null;
int i = 0;
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 30L,
TimeUnit.MICROSECONDS, new ArrayBlockingQueue<Runnable>(3),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
},new ThreadPoolExecutor.CallerRunsPolicy());
ThreadPoolExecutor executor2 = new ThreadPoolExecutor(2, 2, 30L,
TimeUnit.MICROSECONDS, new ArrayBlockingQueue<Runnable>(3),new ThreadPoolExecutor.CallerRunsPolicy());
while ( null != (line = bufferedReader.readLine())){
// new MyFileThread(line,"Thread-"+(++i)).start();
executor.execute(new MyFileThread(line,"Thread-"+(++i)));
}
executor.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("main方法结束");
}
}
class MyFileThread extends Thread{
private String line;
private String threadName;
public MyFileThread(String line,String threadName){
this.line = line;
this.threadName = threadName;
}
@Override
public void run() {
System.out.println(this.threadName+":"+this.line);
}
}