Java多线程2--线程控制

本文详细介绍了Java中线程控制的基本方法,包括sleep()、join()、yield()及优先级设置等,通过实例演示了如何使用这些方法来实现线程间的同步与调度。

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

1、sleep()方法

sleep()是一个静态方法,可以通过类名直接调用,会抛出InterruptedException

public class testSleep {

	public static void main(String[] args) {
		subThread st = new subThread();
		Thread t = new Thread(st);
		t.start();
		try {
			//主进程sleep5s,然后调用thread类的interrupt方法,
			//t catch到InterruptedException,结束死循环
			Thread.sleep(5000);
			t.interrupt();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

}
class subThread implements Runnable{
	public void run() {
		while(true){
			System.out.println("subThread is running");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				return;
			}
		}
	}
}

输出应该为5行“subThread is running”

2、join()方法

将一个进程合并到另一个进程中,相当于直接调用run()方法

public class testJoin {

	public static void main(String[] args) throws InterruptedException {
		subThread1 st = new subThread1();
		Thread t = new Thread(st);
		System.out.println("MainThread:1");
		t.start();
		t.join();
		System.out.println("MainThread:2");
	}

}
class subThread1 implements Runnable{
	public void run() {
		for(int i=0;i<3;i++){
			System.out.println("subThread:"+i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
}
运行结果为:MainThread:1
subThread:0
subThread:1
subThread:2
MainThread:2
3、yield()方法

yield()方法用于让出cpu时间片给其他进程

4、setPriority()和getPriority()

设置进程优先级,优先级越高得到的cpu执行的时间片就越多,具体多少由操作系统分配

进程的优先级最高为10,最低为1,缺省值为5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值