创建线程一般有四种方式:
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
- 使用线程池
下面介绍这几种方式的简单使用
继承Thread类
使用方式:
(1)创建一个类继承Thread类
(2)重写run()方法
(3)调用start()方法开启线程
public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("继承Thread类的线程");
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
// 开启线程
threadDemo.start();
System.out.println("主线程");
}
}
实现Runnable接口
使用方式:
(1)创建一个类实现Runnable接口
(2)实现run()方法
(3)调用start()方法开启线程
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口的线程");
}
public static void main(String[] args) {
RunnableDemo runnableDemo = new RunnableDemo();
Thread thread = new Thread(runnableDemo);
// 启动线程
thread.start();
System.out.println("主线程");
}
}
实现Callable接口
使用方式:
(1)创建一个类实现Callable接口
(2)实现call()方法
(3)调用start()方法开启线程
注:实现Callable接口的线程执行结束后会有返回值;返回值的类型在实现Callable接口的时候定义
public class CallableDemo implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("实现Callable接口的线程");
return "success";
}
public static void main(String[] args) {
CallableDemo callableDemo = new CallableDemo();
FutureTask<String> task = new FutureTask<String>(callableDemo);
Thread thread = new Thread(task);
// 开启线程
thread.start();
System.out.println("主线程");
try {
// 获取线程执行结果
System.out.println(task.get());
} catch (InterruptedException e) {
System.out.println("InterruptedException");
} catch (ExecutionException e) {
System.out.println("ExecutionException");
}
}
}
使用线程池创建
使用方式:
(1)创建一个自定义参数的线程池
(2)调用execute()方法执行创建的线程
(3)关闭线程池
public class ThreadPoolDemo {
/**
* 核心线程数
*/
private static final int CORE_SIZE = 5;
/**
* 最大线程数
*/
private static final int MAXIMUM_POOL_SIZE = 10;
/**
* 大于核心线程数的多余空闲线程的存活时间
*/
private static final long KEEP_ALIVE_TIME = 20L;
/**
* 时间单位,可根据TimeUnit自定义设置
*/
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
/**
* 阻塞队列,可自定义类型
*/
private static final BlockingQueue<Runnable> BLOCKING_QUEUE = new ArrayBlockingQueue<>(20);
public static void main(String[] args) {
// 自定义一个线程池
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(CORE_SIZE, MAXIMUM_POOL_SIZE,
KEEP_ALIVE_TIME, TIME_UNIT, BLOCKING_QUEUE);
for (int i = 0; i < 6; i++) {
threadPoolExecutor.execute(()->{
System.out.println("线程:" + Thread.currentThread().getName() + "正在执行...");
});
}
// 关闭线程池
threadPoolExecutor.shutdown();
}
}
总结
目前使用最多的是使用线程池创建线程的方式;因为使用线程池管理线程,省去了频繁的创建和销毁线程的时间;
note:有疑问请大家留言,谢谢