ThreadFactory线程工厂

版权声明:未经允许禁止转载 https://blog.csdn.net/weixin_38481963/article/details/88376578

看一下这个接口的源码

public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);
}

该接口的目的是定制一个线程,可以设置线程的优先级、名字、是否后台线程、状态等。
输入:继承Runnable接口的实例对象
输出:定制的线程,如果被拒绝,则返回null;

测试:

import java.util.concurrent.*;

class Task implements Runnable {
    public void run(){
        System.out.println(Thread.currentThread().getName()+"   isDaemon:"+Thread.currentThread().isDaemon());
    }
}
public class ThreadFactoryDemo implements ThreadFactory {
    private int id = 0;
    public Thread newThread(Runnable r){
        Thread t = new Thread(r);
        t.setName("Thread-Name:" + id++);
        t.setDaemon(true);
        return t;
    }
    public static void main(String []args)throws InterruptedException{
        ExecutorService exe = new ThreadPoolExecutor(5, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(),
                new ThreadFactoryDemo());
        for(int i=0;i<5;i++)
        {
            exe.execute(new Task());
        }
        exe.shutdown();
        TimeUnit.MILLISECONDS.sleep(1000);
    }
}


结果:

Thread-Name:2   isDaemon:true
Thread-Name:0   isDaemon:true
Thread-Name:1   isDaemon:true
Thread-Name:4   isDaemon:true
Thread-Name:3   isDaemon:true

我们设置了加入到线程池中每个线程的名字和是否后台线程。

猜你喜欢

转载自blog.csdn.net/weixin_38481963/article/details/88376578
今日推荐