线程池测试

本文探讨了Java线程池如果未关闭,会导致主线程无法正常结束,因为核心线程会保持活跃。通过设置线程为守护线程,虽然允许主线程结束,但仍然需要关闭线程池确保所有任务执行完毕。示例代码展示了如何创建和使用线程池。
摘要由CSDN通过智能技术生成

线程池如果不关闭,则主线程无法终止,因为线程池中的核心线程永远不会被回收,除非关闭线程池,或者应用程序终止。
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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值