Java——线程启动

本文探讨了Java中线程启动的方法,包括让测试类直接继承Thread类和实现Runnable接口的区别。推荐使用实现Runnable接口,因为它提供更大的灵活性,允许类同时实现其他接口或继承其他类。此外,start()方法用于线程的同步执行,而run()方法确保先执行其所在线程的run()方法。

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

方法一:

public class Test implements Runnable{	
	public void run() {
		System.out.println("线程启动!");
	}
	public static void main(String[] args) {
		Test thead = new Test();
		thead.run();
		//thead.start();不能调用start方法
	}	
}
输出结果:线程启动!

public class Test implements Runnable{	
	public void run() {
		System.out.println("线程启动!");
	}
	public static void main(String[] args) {
		Test thead = new Test();
		Thread t = new Thread(thead);
		thead.run();
		t.start();
	}	
}
输入结果:线程启动!
            线程启动!
public class Test implements Runnable{	
	public void run() {
		System.out.println("线程启动!");
	}
	public static void main(String[] args) {
		Test thead = new Test();
		Thread t = new Thread(thead);
		t.run();
		t.start();
	}	
}

输入结果:线程启动!
    线程启动!
由以上看出,start()方法存在于Thread这个类中,想要调用start()方法必须使用Thread这个类。
方法二:

public class Test extends Thread{	
	public void run() {
		System.out.println("线程启动!");
	}
	public static void main(String[] args) {
		Test thead = new Test();
		thead.start();
	}	
}

让测试类Test直接继承Thread类,就不用实例化Thread对象,而直接调用start方法。
PS:1.推荐使用实现Runnable接口,类实现了Runnable接口还能实现或者继承其他接口或者类,使用起来比较灵活方便。
          2.start()是使线程之间同步执行
               run()是使run()方法先执行,后再执行其他线程





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值