Java牛角尖【008】: 可以通过调用一个线程的run方法启动一个线程吗?

本文探讨了Java中启动线程的正确方式,指出直接调用run方法与调用start方法的区别,并通过示例代码展示了这两种方式下线程执行的不同表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  我们知道,我们通过调用线程的start方法启动一个线程,那么,我们可以直接调用run方法来启动一个线程吗?

  先看下面一段代码:

public class Test { public static void main(String[] args) { // TODO Auto-generated method stub TestThread tt = new TestThread(); tt.run(); } } class TestThread extends Thread { static int i = 0; final static int MAX_I = 10; @Override public void run() { // TODO Auto-generated method stub while (i < MAX_I) { System.out.println(i++); } } }

  运行结果如下:

0 1 2 3 4 5 6 7 8 9

  或许有人会得出结论,这样启动一个线程是可以的,我们再对程式稍做修改,大家就会发现一个问题:

public class Test { public static void main(String[] args) { // TODO Auto-generated method stub TestThread tt = new TestThread(); tt.run(); System.out.println("Printed by main thread"); } } class TestThread extends Thread { static int i = 0; final static int MAX_I = 10; @Override public void run() { // TODO Auto-generated method stub while (i < MAX_I) { System.out.println(i++); } } }

  这里只在主线程中加入了一行代码,打印一行"Printed by main thread",运行代码,结果如下:

0 1 2 3 4 5 6 7 8 9 Printed by main thread

  熟练多线程开发的要发现问题了,为什么"Printed by main thread"会打印在最后一行呢?TestThread类中一直持有时间段吗?

  我们对上面的代码进行分析,其实非常简单,这只是一个普通的类中方法的调用,其实是一个单线程的执行,我们来修改代码进一步验证这一点:

public class Test { public static void main(String[] args) { // TODO Auto-generated method stub TestThread tt = new TestThread(); tt.run(); System.out.println(Thread.currentThread().getName()); System.out.println("Printed by main thread"); } } class TestThread extends Thread { static int i = 0; final static int MAX_I = 10; @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName()); while (i < MAX_I) { System.out.println(i++); } } }

  这段代码分别在主线程和我们的TestThread的方法中打印当前线程名字,运行结果如下:

main 0 1 2 3 4 5 6 7 8 9 main Printed by main thread

  在TestThread类和主线程中运行的是同一个线程,说明在直接调用run时是不能使用多线程的,那么把上面的run方法调用改为start方法的调动再看一下:

public class Test { public static void main(String[] args) { // TODO Auto-generated method stub TestThread tt = new TestThread(); tt.start(); System.out.println(Thread.currentThread().getName()); System.out.println("Printed by main thread"); } } class TestThread extends Thread { static int i = 0; final static int MAX_I = 10; @Override public void run() { // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName()); while (i < MAX_I) { System.out.println(i++); } } }

  运行结果如下:

main Thread-0 0 1 2 3 4 5 6 7 8 Printed by main thread 9

  很明显,这才是我们想看到的结果,所以结论是只有调用Thread的start方法,将线程交由JVM控制,才能产生多线程,而直接调用run方法只是一个普通的单线程程式。

 

  下一篇: Java牛角尖【009】: 多线程中synchronized的锁定方式

转载于:https://www.cnblogs.com/moonsnow/archive/2009/06/11/6226853.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值