线程的sleep,join,yield方法

本文深入探讨了Java线程状态转换及其关键操作,包括睡眠、阻塞解除、线程合并和让出CPU。通过具体示例阐述了如何使用Thread类的方法来实现多线程任务的高效执行。

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

线程状态转换:


创建->start()->就绪状态<-->调度->运行状态->终止
|箭头                |箭头
|向上  |向下
   阻塞解除<-阻塞状态<—导致阻塞的事件 


·sleep方法
   ·可以调用Thread的静态方法:
    public static void sleep(long millis) throws InterruptedException


    使得当前线程休眠(暂停执行millis毫秒)
 
  ·由于是静态方法,sleep可由类名直接调用:

Thread.sleep(....)


举例:
<span style="font-size:14px;">public class TestTnterrupt {
	public static void main(String args[]) {
		MyThread myThread = new MyThread();
		thread.start();
		try{Thread.sleep(10000);}
		catch{InterruptedException e}{}
		thread.interrupt();//终止线程
	}
}
class MyThread extends Thread {
	public void run(){
		while(true){
			System.out.println("...."+new Date()+".....");
			try{
				sleep(1000);
			}catch(InterruptedException e){
			return;
			}
		}
	}
}</span>


.join方法


   ·合并某个线程


举例:

<span style="font-size:14px;">public class TestJoin {
	public static void main(String args[]) {
		MyThread thread = new MyThread("adcdb");
		thread.start();
		try {
			thread.join();
		}catch(InterruptedException e) {}
		for(int i=0;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=0;i<10;i++) {
			System.out.println("i am "+getName());
		}
		try {
			sleep(1000);
		}catch(InterruptedException e) {
		return;
		}
	}
}
</span>

注释:把MyThread线程执行完了再执行主线程


·yield方法


   .让出CPU,给其他线程执行的机会


举例:

<span style="font-size:14px;">public class TestYield {
	public static void main(String args[]) {
		MyThread t1 = new MyThread("t1");
		MyThread t2 = new MyThread("t2");
		t1.start();
		t2.start();
	}
}
class MyThread extends Thread {
	MyThread(String s) {
		super(s);
	}
	public void run() {
		for(int i=0;i<=100;i++) {
			System.out.println(getName()+": "+i);
			if(i%10==0) {
				yield();
			}
		}
	}
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值