线程池:ThreadFactory

ThreadFactory 简单使用

有时需要对线程池中创建的线程属性进行定制化,这时就得需要配置ThreadFactory线程工厂。

MyRunnable

package threads.excutors.test4;
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+" "+System.currentTimeMillis());
            Thread.sleep(4000);
            System.out.println(Thread.currentThread().getName()+" "+System.currentTimeMillis());
        }catch (InterruptedException ex){
            ex.printStackTrace();
        }
    }
}
View Code

MyThreadFactory

package threads.excutors.test4;


import java.util.Date;
import java.util.concurrent.ThreadFactory;

public class MyThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        Thread newThread=new Thread(r);
        newThread.setName("this is a test"+new Date());
        return newThread;
    }
}
View Code

Test

package threads.excutors.test4;


import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args) {
        MyRunnable myRunnable=new MyRunnable();
        ThreadPoolExecutor poolExecutor=new ThreadPoolExecutor(2,9999,9999L,
                TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>(),
                new MyThreadFactory());//使用构造函数传递自定义的线程工厂
        poolExecutor.execute(myRunnable);

        //采用另外一种方式来传递自定义的线程工厂
        poolExecutor.setThreadFactory(new MyThreadFactory());
        poolExecutor.execute(myRunnable);

    }


}
View Code

使用自定义工厂时,线程如果出现异常完全可以定义去处理

package threads.excutors.test4;


import java.util.Date;
import java.util.concurrent.ThreadFactory;

public class MyThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        Thread newThread=new Thread(r);
        newThread.setName("this is a test"+new Date());

        //使用自定义工厂时,线程如果出现异常完全可以定义去处理
        newThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("our self define exception handle:"+t.getName()+e.getMessage());
            }
        });
        return newThread;
    }
}
View Code

 

posted @ 2020-05-15 11:32  弱水三千12138  阅读(3076)  评论(0)    收藏  举报