Java——线程sleep()join()yield()方法

本文通过两个Java示例对比分析了线程中的join()方法与sleep()方法的作用及用法。join()方法使子线程等待主线程执行完成后再运行,而sleep()方法则使当前线程暂停执行指定时间。

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

一:

public class Test{	
	public static void main(String[] args) {
		Mythread t = new Mythread("aaaa");
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for(int i=1;i<=10;i++){
			System.out.println("i am main thread");
		}
	}	
}	

class Mythread extends Thread{
		Mythread(String s){
			super(s);
		}
		public void run(){
			for(int i=1;i<=10;i++){
				System.out.println("i am" + getName());
				try {
					sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}return;
				}
			}
输出结果:i amaaaa
    i amaaaa
            i amaaaa
  i am main thread
  i am main thread
  i am main thread
二、

public class Test{	
	public static void main(String[] args) {
		Mythread t = new Mythread("aaaa");
		t.start();
		for(int i=1;i<=3;i++){
			System.out.println("i am main thread");
		}
	}	
}	


class Mythread extends Thread{
		Mythread(String s){
			super(s);
		}
		public void run(){
			for(int i=1;i<=3;i++){
				System.out.println("i am" + getName());
			}
			try {
				sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}return;
			}
		}
输出结果:
i am main thread
i am main thread
i am main thread
i amaaaa
i amaaaa
i amaaaa


通过一、二比较得:
join()方法让此线程加入到主线程之中,即等待主线程执行完毕之后再执行子线程。
sleep()方法会让线程睡眠指定的毫秒数。
yield()方法让出CPU,让其他线程执行。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值