Executor
Executor
用于提交任务,Executor将线程的创建与执行机制进行解偶
public interface Executor {
void execute(Runnable command);
}
我们定义一个任务,然后自己创建线程去执行任务,这样线程的创建就与任务执行产生了耦和。
public class ExecutorTest {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("执行我的任务");
}
}
}
输出:
执行我的任务
使用Executor,我们只需要创建任务,然后由Executor代替我们去创建线程去执行任务。
public class ExecutorTest {
public static void main(String[] args) {
new TaskExecutor().execute(new MyRunnable());
}
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("执行我的任务");
}
}
static class TaskExecutor implements Executor{
@Override
public void execute(Runnable command) {
new Thread(command).start();
}
}
}
输出:
执行我的任务
但是Executor并不严格要求任务执行是异步的(大多数情况是异步执行),Executor可以在当前线程立即执行任务,比如:
public class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
ThreadFactory
而Executor通常也不是自己去创建线程,而是通过线程工厂来进行创建线程,比如ThreadPerTaskExecutor组合了一个线程工厂,把线程的创建交给线程工厂
public final class ThreadPerTaskExecutor implements Executor {
private final ThreadFactory threadFactory;
public ThreadPerTaskExecutor(ThreadFactory threadFactory) {
if (threadFactory == null) {
throw new NullPointerException("threadFactory");
} else {
this.threadFactory = threadFactory;
}
}
public void execute(Runnable command) {
this.threadFactory.newThread(command).start();
}
}
通过ThreadFactory创建线程,ThreadFactory不仅仅是创建线程,还会设置线程组、线程的名字、线程的优先级等等
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}