java多线程的四种实现方式
java多线程的四种实现方式
1. 继承Thread类,重写run方法
2. 实现Runnable接口,实现run方法
3. 实现Callable接口,重写call方法,利用FutureTask可以获取线程返回值
4. 使用Executor框架创建线程池
1. 继承Thread类,重写run方法
/** * 继承Thread类,重写run方法 * * @Author: zq980328 * @Create: 2022/3/22 14:50 */public class ThreadTest extends Thread { @Override public void run() { System.out.println("run===" + Thread.currentThread().getId()); super.run(); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { ThreadTest threadTest = new ThreadTest(); threadTest.start(); } }}
2. 实现Runnable接口,实现run方法
/** * 实现Runnable接口,实现run方法 * * @Author: zq980328 * @Create: 2022/3/22 14:50 */public class RunnableTest implements Runnable { @Override public void run() { System.out.println("run===" + Thread.currentThread().getId()); } public static void main(String[] args) { RunnableTest runnableTest = new RunnableTest(); for (int i = 0; i < 10; i++) { Thread thread = new Thread(runnableTest); thread.start(); } }}
Java8 lambda写法
Thread thread = new Thread(() -> { System.out.println("run===" + Thread.currentThread().getId());});thread.start();
3. 实现Callable接口,重写call方法,利用FutureTask可以获取线程返回值
/** * 实现Callable接口,重写call方法,利用FutureTask可以获取线程返回值 * * @Author: zq980328 * @Create: 2022/3/22 15:13 */public class CallableTest implements Callable { @Override public Object call() { System.out.println("run===" + Thread.currentThread().getId()); return "success" + Thread.currentThread().getId(); } public static void main(String[] args) throws ExecutionException, InterruptedException { CallableTest callableTest = new CallableTest(); for (int i = 0; i < 10; i++) { FutureTask<Object> future = new FutureTask<Object>(callableTest); Thread thread = new Thread(future); thread.start(); // 获取返回值 future.get(); } }}
4. 使用Executor框架创建线程池
使用ThreadPoolExecutor创建自定义线程池
/** * 使用ThreadPoolExecutor创建自定义线程池 * * @Author: zq980328 * @Create: 2022/3/22 15:33 */public class ExecutorsTest { public static void main(String[] args) { // ExecutorService executorService = Executors.newCachedThreadPool(); Thread thread = new Thread(() -> { System.out.println("run===" + Thread.currentThread().getId()); }); for (int i = 0; i < 10; i++) { executorService.execute(thread); // executorService.submit可以获取线程返回值 // Future submit = executorService.submit(thread); } }}
使用Executors工具类创建默认线程池
/** * 使用Executors工具类创建默认线程池 * * @Author: zq980328 * @Create: 2022/3/22 15:33 */public class ExecutorsTest { public static void main(String[] args) { // 使用Executors工具类创建默认线程池 ExecutorService executorService = Executors.newCachedThreadPool(); Thread thread = new Thread(() -> { System.out.println("run===" + Thread.currentThread().getId()); }); for (int i = 0; i < 10; i++) { executorService.execute(thread); // executorService.submit可以获取线程返回值 // Future submit = executorService.submit(thread); } }}