1、继承Thread
class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread");
}
}
public static void test(){
MyThread thread = new MyThread();
thread.start();
}
2、实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable");
}
}
public static void test2(){
MyRunnable runnable = new MyRunnable();
new Thread(runnable).start();
}
3、实现Callable接口 + FeatureTask 可以拿到任务的返回结果
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 10/2;
}
}
public static void test3() throws ExecutionException, InterruptedException {
MyCallable runnable = new MyCallable();
FutureTask<Integer> task = new FutureTask<>(runnable);
new Thread(task).start();
System.out.println(task.get());
}
4、使用线程池,直接给线程池提交任务
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
参数解释:
corePoolSize:核心线程数
maximumPoolSize:最大线程数
keepAliveTime:多余核心线程数得线程存活时间
unit:时间单位
workQueue:阻塞队列,如果任务很多,可以先把任务放到队列中,当线程执行完当前任务会自动从队列获取新任务
threadFactory:线程得创建工厂
handler:如果线程满了。按照我们指定得拒绝策略拒绝执行任务
线程池执行顺序:
1、线程池创建,创建核心线程,准备接收任务
2、没有空闲核心线程,就把任务放到队列中
3、队列满了之后,在最大线程数范围内创建新得线程处理任务
4、最大线程数也满了,就开始使用拒绝策略处理任务
5、任务执行完,除了核心线程,空闲得线程会在存活时间之后释放