java多线程run()与start()区别

Thread类中run()和start()方法的区别如下:
run()方法:在本线程内调用该Runnable对象的run()方法,可以重复多次调用;

start()方法:启动一个线程,调用该Runnable对象的run()方法,不能多次启动一个线程

public class Run_Start {

	public static void main(String[] args) throws InterruptedException {
		System.out.println("main thread start!");
		Thread thread = new MyTestThread();
		thread.run();//thread.start();
		for(int i=0;i<20;i++)
		{
			System.out.println("main thread");
		}
		System.out.println("main thread end!");
	}
}

class MyTestThread extends Thread
{
	@Override
	public void run() {
		 for (int i = 0; i < 100; i++) {
             System.out.println("Thread new "+i);
         }
	}
}

1、run()和其他方法的调用没任何不同,main方法按顺序执行了它

main thread start!
Thread new 0
Thread new 1
Thread new 2
Thread new 3
Thread new 4
Thread new 5

......

Thread new 99

main thread
main thread

......

main thread end!


2、start()方法重新创建了一个线程,该线程的执行与主线程是并行的。在main方法执行结束后,由于start()方法创建的线程没有运行结束,因此主线程未能退出,直到线程thread也执行完毕.这里要注意,默认创建的线程是用户线程(非守护线程)

main thread start!
main thread
main thread

......

Thread new 0
Thread new 1
Thread new 2
Thread new 3
Thread new 4
Thread new 5
Thread new 6
Thread new 7
Thread new 8
Thread new 9
main thread end!
Thread new 10
Thread new 11
Thread new 12
Thread new 13

......

Thread new 99

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值