Java创建线程的4种方式
继承Thread类,重写run方法
Thread类实现了Runnable接口(只有一个没有返回值的run方法)。
public class ThreadDemo extends Thread {
public ThreadDemo(String name) {
super(name);
}
@Override
public void run() {
System.out.println(getName());
}
public static void main(String[] args) {
ThreadDemo thread1 = new ThreadDemo("thread1");
ThreadDemo thread2 = new ThreadDemo("thread2");
thread1.start();
thread2.start();
}
}
运行结果
thread2
thread1
实现Runnable接口,重写run方法
相比于继承Thread类,通过同一个实现了Runnable接口的对象来构造Thread对象,可以避免单继承的缺陷和实现资源共享。
public class ThreadDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadDemo thread = new ThreadDemo();
Thread thread1 = new Thread(thread, "thread1");
Thread thread2 = new Thread(thread, "thread2");
thread1.start();
thread2.start();
}
}
运行结果
thread1
thread2
实现Callable接口,重写call方法
Callable接口只有一个call方法。相比于run方法,有返回值,且返回值支持泛型,可以抛出异常,借助FutureTask类来获取返回结果。
针对Runnable或者Callable任务,Future接口支持判断任务是否完成、中断任务、获取任务执行结果(get方法阻塞直到任务返回结果),唯一实现类是FutureTask。
FutureTask实现了RunnableFuture接口,RunnableFuture接口继承了Runnable和Future接口。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo implements Callable<String> {
@Override
public String call() throws Exception {
return "thread";
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
FutureTask<String> futureTask = new FutureTask<>(threadDemo);
new Thread(futureTask).start();
String s = "";
try {
s = futureTask.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println(s);
}
}
运行结果
thread
使用ThreadPoolExecutor来创建线程池
ThreadPoolExecutor实现了Executor接口。
使用线程池,降低资源消耗,提高响应速度,提高线程的可管理性。
基于初始容量为10的有界任务队列来创建核心容量为10、最大容量为20、线程存活时间为1分钟的线程池
import java.util.concurrent.*;
public class ThreadDemo implements Runnable {
public static void main(String[] args) {
BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(10);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
10, 20, 1, TimeUnit.MINUTES, blockingQueue, Executors.defaultThreadFactory());
for (int i = 0; i < 10; i++) {
threadPoolExecutor.submit(new ThreadDemo());
}
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
运行结果
pool-1-thread-2
pool-1-thread-6
pool-1-thread-3
pool-1-thread-9
pool-1-thread-1
pool-1-thread-4
pool-1-thread-7
pool-1-thread-5
pool-1-thread-8
pool-1-thread-10