JAVA多线程有哪几种实现方式呢?
2022/4/23 1:12:49
本文主要是介绍JAVA多线程有哪几种实现方式呢?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
下文笔者讲述java中多线程的实现方式,如下所示:
JAVA中多线程主要有以下实现方式: 1.继承Thread类 2.实现Runnable接口 3.使用ExecutorService、Callable、Future实现有返回结果的多线程 注意事项: 方式1和方式2线程运行完毕后,是没有返回值
继承Thread类实现多线程
注意事项: 1.Thread本质上也是实现了Runnable接口的一个实例 Thread它指一个线程实例 2.启动Thread类,需使用start()方法 start()方法是一个native方法 它的功能:启动一个新线程,并执行run()方法 3.使用Thread生成多线程,我们只需继承Thread类,重写run方法即可例:
public class MyThread extends Thread { public void run() { System.out.println("MyThread.run()"); } } //开启两个线程 MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); myThread1.start(); myThread2.start();
使用Runnable接口方式实现多线程
例://定义一个多线程 public class MyThread extends TestClass implements Runnable { public void run() { System.out.println("MyThread.run()"); } } //启动线程 MyThread myThread = new MyThread(); Thread thread = new Thread(myThread); thread.start();
使用ExecutorService、Callable、Future实现有返回结果的多线程
ExecutorService、Callable、Future 对象都属于Executor框架中的功能类例:多线程带返回值
import java.util.concurrent.*; import java.util.Date; import java.util.List; import java.util.ArrayList; /** * 有返回值的线程 */ @SuppressWarnings("unchecked") public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("----程序开始运行----"); Date date1 = new Date(); int taskSize = 5; // 创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(taskSize); // 创建多个有返回值的任务 List<Future> list = new ArrayList<Future>(); for (int i = 0; i < taskSize; i++) { Callable c = new MyCallable(i + " "); // 执行任务并获取Future对象 Future f = pool.submit(c); // System.out.println(">>>" + f.get().toString()); list.add(f); } // 关闭线程池 pool.shutdown(); // 获取所有并发任务的运行结果 for (Future f : list) { // 从Future对象上获取任务的返回值,并输出到控制台 System.out.println(">>>" + f.get().toString()); } Date date2 = new Date(); System.out.println("----程序结束运行----,程序运行时间【" + (date2.getTime() - date1.getTime()) + "毫秒】"); } } class MyCallable implements Callable<Object> { private String taskNum; MyCallable(String taskNum) { this.taskNum = taskNum; } public Object call() throws Exception { System.out.println(">>>" + taskNum + "任务启动"); Date dateTmp1 = new Date(); Thread.sleep(1000); Date dateTmp2 = new Date(); long time = dateTmp2.getTime() - dateTmp1.getTime(); System.out.println(">>>" + taskNum + "任务终止"); return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】"; } }
这篇关于JAVA多线程有哪几种实现方式呢?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?