关闭

线程池使用之ExecutorService

358人阅读 评论(0) 收藏 举报
分类:

1、场景:非周期性执行某一任务

2、文件处理类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileProcess
{
    //单例模式
    private static FileProcess instance = new FileProcess();
    
    public static FileProcess getInstance()
    {
        return instance;
    }
    
    private ExecutorService threadPool;
    
    //线程池中的线程数
    private int threadNum = 1;
    
    public void start()
    {
        //新建一个线程池
        threadPool = Executors.newFixedThreadPool(threadNum);
    }
    
    //关闭线程池
    public void stop()
    {
        if (null != threadPool)
        {
            threadPool.shutdown();
            threadPool = null;
        }
        
    }
    
    //测试ExecutorService
    public void testFun()
    {
        threadPool.execute(new FileProcessTask("log.txt"));
    }
}

class FileProcessTask implements Runnable
{
    private String fileName;
    
    public FileProcessTask(String fileName)
    {
        this.fileName = fileName;
    }

    @Override
    public void run()
    {
        System.out.println("process the file:" + fileName);
    }
    
}

3、测试代码

public class Test
{
    
    public static void main(String[] args)
    {
        FileProcess fileProcess = FileProcess.getInstance();
        fileProcess.start();
        fileProcess.testFun();
        fileProcess.stop();
    }
    
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:225658次
    • 积分:4091
    • 等级:
    • 排名:第7558名
    • 原创:156篇
    • 转载:321篇
    • 译文:0篇
    • 评论:8条
    最新评论