我是靠谱客的博主 害怕斑马,这篇文章主要介绍Java线程启动为什么要用start()而不是run()?,现在分享给大家,希望可以做个参考。

1、直接调用线程的run()方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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()方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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()); } }

startVSrun1.JPG 可以看到在,在执行完t1.start()这一行之后,主线程立马继续往下执行,休眠2s后输出内容。 也就是说,t1线程和主线程是异步执行的,主线程在线程t1的start()方法执行完成后继续执行后面的内容,无需等待run()方法体的内容执行完成。

3、总结

  • 1、开启一个线程必须通过start()方法,直接调用run()方法并不会创建线程,而是同步执行run()方法中的内容。
  • 2、如果通过传入一个Runnable对象创建线程,线程会执行Runnable对象的run()方法;否则执行自己本身的run()方法。
  • 3、不管是实现Runnable接口还是继承Thread对象,都可以重写run()方法,达到执行设定的任务的效果。

到此这篇关于线程启动为什么要用start()而不是run()?的文章就介绍到这了,更多相关start()与run()内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是害怕斑马最近收集整理的关于Java线程启动为什么要用start()而不是run()?的全部内容,更多相关Java线程启动为什么要用start()而不是run()内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(134)

评论列表共有 0 条评论

立即
投稿
返回
顶部