为什么启动一个线程要用start()而不是run()?
作者:佚名 来源:第七下载 更新:2021-12-11 17:14:14 阅读:次
用手机看
- Android版
1、直接调用线程的run()方法
public class TestStart {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
@Override
public void run() {
System.out.println("Thread t1 is working..."+System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.run();
Thread.sleep(2000);
System.out.println("Thread Main is doing other thing..."+System.currentTimeMillis());
}
}
可以看到主线程在t1.run()运行之后再过三秒才继续运行,也就是说,直接在主方法中调用线程的run()方法,并不会开启一个线程去执行run()方法体内的内容,而是同步执行。
2、调用线程的start()方法
public class TestStart {public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
@Override
public void run() {
System.out.println("Thread t1 is working..."+System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
Thread.sleep(2000);
System.out.println("Thread Main is doing other thing..."+System.currentTimeMillis());
}
}
可以看到在,在执行完
t1.start()
这一行之后,主线程立马继续往下执行,休眠2s后输出内容。 也就是说,t1线程和主线程是异步执行的,主线程在线程t1的start()方法执行完成后继续执行后面的内容,无需等待run()方法体的内容执行完成。3、总结
1、开启一个线程必须通过start()方法,直接调用run()方法并不会创建线程,而是同步执行run()方法中的内容。
2、如果通过传入一个Runnable对象创建线程,线程会执行Runnable对象的run()方法;否则执行自己本身的run()方法。
3、不管是实现Runnable接口还是继承Thread对象,都可以重写run()方法,达到执行设定的任务的效果。
?
相关文章- 英雄联盟手游3.4版本新英雄介绍 lol手游3.4新英雄有哪些 01-10
- lol手游3.4版本英雄调整介绍 英雄联盟手游3.4英雄调整有哪些 01-10
- 英雄联盟手游3.4版本新装备汇总 lol手游3.4版本新装备是什么 01-10
- 风来之国菜谱最新2022 风来之国菜谱大全 01-10
- 少女战争兑换码最新2022 少女战争兑换码大全 01-10
- 战神新世纪兑换码最新2022 战神新世纪兑换码大全 01-10
- 抖音喵了个喵小程序入口地址 喵了个喵游戏入口 01-10
- 抖音贱猫消消游戏入口 贱猫消消小游戏入口在哪 01-10
- 王者荣耀新赛季s29赛季皮肤介绍 王者荣耀新赛季s29赛季皮肤是谁的 01-10
?
热点推荐 ?
赞助 ?
网友跟帖吐槽