当前位置:网站首页>线程的创建方式
线程的创建方式
2022-08-02 06:21:00 【俚语h。】
一、继承Thread类
子类可以继承Thread类,重写Thread类的run()方法从而创建线程
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行了~~~");
}
public static void main(String[] args) {
Thread1 thread1=new Thread1();
thread1.start();
}
}
这种方式直接创建子类的实例化对象,调用start()方法既可启动线程
二、实现Runnable接口
子类实现Runnable接口,重写run()方法,这里实际上还是重写的Thread类的run()方法
/** * @author :xuezhiqian * @description:TODO:实现Runnable接口 * @date :2022/8/1 9:47 */
public class Thread2 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行了~~~~~");
}
public static void main(String[] args) {
//需要创建一个Thread对象,将实现了Runnable接口类的对象传进去
Thread thread=new Thread(new Thread2());
thread.start();
}
}
也可以使用匿名内部类创建线程
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 执行了~~~");
}
},"匿名内部类线程");
thread.start();
同时这种只有一个抽象方法的接口,可以使用Lambda表达式
Thread thread2=new Thread(()->{
System.out.println("Lambda表达式");
});
thread2.start();
三、实现Callable接口
实现Callable接口,重写它的call()方法
注意:
Callable接口是有返回值的,要获取他的返回值,需要结合FutureTask
/** * @author :xuezhiqian * @description:TODO:实现Callable<E>接口 * 这是一个有返回值的 * @date :2022/8/1 9:52 */
public class Thread3 implements Callable<Integer>{
//重写call方法
@Override
public Integer call() throws Exception {
Integer result=10;
System.out.println(Thread.currentThread().getName()+"Callable接口执行了~~~ " );
return result;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//需要使用FutureTask<E>包装实现了Callable接口类的实例化对象
FutureTask<Integer> task=new FutureTask<>(new Thread3());
Thread thread=new Thread(task);
thread.start();
//获取返回值需要调用FutureTask的get()方法
Integer result=task.get();
System.out.println(result);
}
}
四、创建定时器线程
public class TimmerThread {
public static void main(String[] args) {
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时器线程执行了~~~");
}
},3000,3000);
//delay:延迟多久开始执行(例如这个代码就是延迟三秒开始执行第一次);
//period:执行周期,就是隔多久执行一次
}
}
补充:
直接调用run()方法和调用start()方法有什么区别?
我们的目的是创建一个子线程去执行run()方法中的内容,主线程继续向下执行。
而直接在主进程中调用run(),就相当于调用了一个普通方法,主程序会进入run()方法,执行完毕后退出run()方法继续执行主方法,就没有新线程的产生。而调用start()方法,会产生一个新的线程,主线程不会进入run()方法,run()方法的执行交由新线程去执行,主线程继续向下顺序执行。
边栏推荐
- Detailed explanation of 9 common reasons for MySQL index failure
- 解决C#非静态字段、方法或属性“islandnum.Program.getIslandCount(int[][], int, int)”要求对象引用
- Project development specification
- 速看!PMP新考纲、PMBOK第七版解读
- JS初识高阶函数和函数柯里化
- Nodejs installation and global configuration (super detailed)
- Nodejs installation tutorial
- Servlet
- Redis 常用命令和基本数据结构(数据类型)
- MySQL high-level --- storage engine, index, lock
猜你喜欢

【npm install 报错问题合集】- npm ERR! code ENOTEMPTY npm ERR! syscall rmdir

About the local server problem after ue4.27 pixel streaming package

Nodejs installation and global configuration (super detailed)

交换网络----三种生成树协议

nacos源码启动找不到istio包

Specified URL is not reachable,caused by :‘Read timed out

Unity Shader学习(七)纹理图像的简单使用
![[Dataset][VOC] Eyewear dataset 6000 in VOC format](/img/66/37f76d9ce5d5f68d6ea0e18710fa04.png)
[Dataset][VOC] Eyewear dataset 6000 in VOC format

At age 94, pioneer Turing award winner, computational complexity theory, Juris Hartmanis, died

Redis 常用命令和基本数据结构(数据类型)
随机推荐
In-depth analysis of the initialization of member variables and local variables
有点奇怪!访问目的网址,主机能容器却不行
Unity Shader学习(七)纹理图像的简单使用
实例027:递归输出
The stock price has repeatedly hit new lows, and the real estate SaaS giant is in trouble. How should Mingyuan Cloud transform and save itself?
typescript ‘props‘ is declared but its value is never read 解决办法
request.getSession(),的故事
正则表达式的理解学习
C# FileInfo class
Swagger的简单介绍,集成,以及如何在生产环境中关闭swagger,在测试和开发环境中自动打开
分离轴定理SAT凸多边形精确碰撞检测
HCIP 第三天实验
MPLS的相关技术
实例032:反向输出II
Node installation and environment configuration
Expert Insights | 3 ways to seize innovation opportunities in a downturn
每周推荐短视频:为什么产品开发需要数字化?如何做到数字化?
返回文件名问题
APP special test: traffic test
实例028:递归求等差数列