1.继承Thread:很少使用,因为java单继承的原因
public class ExtendsThread extends Thread{
@Override
public void run() {
System.out.println("线程创建,在这里写代码");
}
public static void main(String[] args) {
Thread t1 = new ExtendsThread();
t1.start();
}
}
2.实现Runnable接口:解决的java单继承的局限
public class ImplRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程创建,在这里写代码");
}
public static void main(String[] args) {
Runnable runnable = new ImplRunnable();
Thread t1 = new Thread(runnable);
t1.start();
}
}
3.实现Callable接口:拥有返回值,也能抛出异常
public class ImplCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("线程创建,在这里写代码");
return 1024;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<>(new ImplCallable());
Thread t1 = new Thread(futureTask);
t1.start();
//获取返回值,但这方法会阻塞
System.out.println(futureTask.get()); //1024
}
}
4.线程池:复用线程,控制最大并发数,管理线程
public class ThreadPool {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(1); //创建固定大小线程池
//ExecutorService executorService = Executors.newCachedThreadPool();创建不定大小线程池,最大为Integer.MAX_VALUE
//ExecutorService executorService = Executors.newSingleThreadExecutor();创建大小为1的线程池
try{
threadPool.execute(() -> {
System.out.println("线程创建,在这里写代码");
});
} finally {
threadPool.shutdown();
}
}
}
但阿里巴巴编程规范里,指出这中创建方式会出现错误,所以我们一般是通过ThreadPoolExecutor自定义线程池
public class MyThreadPool {
public static void main(String[] args) {
// 声明了一个
// 核心线程数为2
// 最大线程数为5
// 空闲线程存活时间 1s
// 阻塞队列采用LinkedBlockingQueue并限制其大小为3
// 拒绝策略为CallerRunsPolicy ---拒绝策略有四种,可以自己去详细了解下
// 的线程池。
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5, 1L,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
try{
threadPool.execute(() -> {
System.out.println("线程创建,在这里写代码");
});
} finally {
threadPool.shutdown();
}
}
}