当前位置:网站首页>实现多线程的三种方法
实现多线程的三种方法
2022-07-23 15:42:00 【张张的store】
实现线程的第一种方式:
编写一个类,直接继承java.lang.Thread,重写run方法
//定义线程类 public class MyThread extends Thread{ public void run(){ } } //创建线程对象 MyThread t = new MyThread(); //启动线程 t.start();怎么创建线程对象?new
怎么启动线程?
调用线程对象的start() 方法
start() 方法的作用是:启动一个分支线程,在JVM中开辟一个新的栈空间,这段代码任务完成之后,瞬间就结束了。这段代码的任务只是为了开启一个新的栈空间,只要新的栈空间开出来了。start()方法就结束了。线程就启动成功了。run方法在分支栈的栈底部,main方法在主栈的栈底部。run和main是平级的
注意
- 亘古不变的道理:方法体中的代码永远都是自上而下的顺序执行的
实现线程的第二种方式
编写一个类,实现java.lang.Runnable接口,实现run方法
//定义一个可运行的类 public class MyRunnable implements Runnable{ public void run(){ } } //创建线程对象 Thread t = new Thread(new MyRunnable()); //启动线程 t.start();注意:第二种方式实现接口比较常用,因为一个类实现了接口,它还可以去继承其他的类,更灵活
实现线程的第三种方式:
- 实现Callable接口
- 优点:可以获取到线程的执行结果
- 缺点:效率比较低,在获取其他线程执行结果的时候,当前线程受阻塞,效率较低
FutureTask task = new FutureTask(new Callable(){
public Object call() throws Exception {
//call()方法就相当于run方法,只不过这个有返回值
//线程执行一个任务,执行之后可能会有一个执行结果
System.out.println("call method begin");
Thread.sleep(1000 * 10);
System.out.println("call method end");
int a = 100;
int b = 200;
return a + b; //自动装箱(300结果变成Integer)
}
})
边栏推荐
- Chi square distribution, analysis of variance
- 为什么香港服务器可以免备案
- ContextLoaderListener vs DispatcherServlet
- WARNING: Your password has expired. Password change required but no TTY available.
- IDEA Download Sources报错 Connection refused的解决方法
- idea debug常用操作
- Multithreaded programming
- Web page basic template
- curl get&post
- rust求两数之和
猜你喜欢

rust统计文件中单词出现的次数

分析一个 .NET 写的 某 RFID标签系统 CPU暴涨

MySQL六十六问,两万字+五十图详解含(答案解析)

Keras之二分类问题

go中的协程原理详解

Seal player IP and machine code and unlock the blocked tutorial

“如今,99.9% 以上的代码都是垃圾!”

Role definition in USB type-C PD CC logic chip

封玩家IP和机器码以及解开被封的教程

New opportunities for cultural tourism in the era of digital intelligence? China Mobile Migu creates "the first island in the yuan universe"
随机推荐
An online frequent fullgc troubleshooting
MongoDB分组取每组中一条数据
LeetCode_动态规划_中等_120.三角形最小路径和
Trust finds the maximum value in the array
C language -- implementation of address book and screentogif
Activity Registration: how to quickly start the open source tapdata live data platform on a zero basis?
LeetCode_ Dynamic programming_ Medium_ 120. Triangle minimum path sum
薪资高压线
MySQL foundation and performance optimization
(十一)STM32——IO引脚复用与映射
CreateFileMapping 函数「建议收藏」
Data concentration analysis and data distribution
Debug: the formal parameter has const modifier, which should be paid attention to
MinGW-w64的安装及配置教程
MySQL massive write problem optimization scheme MySQL parameter tuning
Why can Hong Kong servers be exempted from filing
Microservice avalanche problems and Solutions
mysqldump的各项参数
QT multithread instance and the fifth parameter of connect [easy to understand]
idea debug常用操作