晋南讲堂之Java-线程的调度

线程的调度

1. 线程睡眠(sleep)

  如果需要把当前的线程暂停一段时间,让出CPU的控制权,让其他线程有机会执行,则使用Thread类中的静态方法sleep(),该方法会抛出InterruptedException异常,所以使用该方法需要捕获异常。需要注意的是,线程执行sleep()方法并不会释放对象锁。sleep()方法的签名如下:

public static void sleep(long millis) throws InterruptedException; //在指定的毫秒数millis内让当前正在执行的线程休眠
public static void sleep(long millis,int nanos) throws InterruptedException; //在指定的毫秒数millis和指定的纳秒数nanos内让当前正在执行的线程休眠

如果睡眠过程中被打断,则抛出InterruptedException异常。

2. 线程让步(yield)

  与sleep()方法类似,yield()方法也是Thread方法里的静态方法,调用该方法会暂停当前正在执行的线程,交出CPU权限,但该方法只能让拥有相同优先级或者更高优先级的线程有获取CPU时间片的机会。如果可运行线程队列里的线程都没有当前的线程优先级高,则当前线程会继续执行。调用该方法不会让线程进入阻塞状态,而是让它重回可运行状态。

2. 线程协作(join)

  如果一个线程运行到某个点需要等待另一个线程结束,则可以在该线程内调用另一个线程的join()方法。由于各个线程耗用的时间不一致,有的时候需要等待另一个比较耗时的线程执行完毕后返回结果该线程才能继续执行。

public class ThreadJoin extends Thread {
	public void run(){
		for(int i=0;i<=10;i++){
			System.out.println("子线程%%%");
			try{
				sleep(500);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		ThreadJoin t = new ThreadJoin();
		t.start();
		for(int i=1;i<=10;i++){
			System.out.println("主线程");
			if(i==4){
				try{
				t.join();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			
			}
			try{
				sleep(500);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

  运行结果为:
在这里插入图片描述

2. 线程优先级

  Java中每个线程都有各自的优先级,优先级高的线程运行机会较多,优先级低的线程机会少,但并不是说没有。
  线程的优先级用1-10的数字来表示,默认优先级为5。Java中Thread类定义了三个常量,如下所示:

static int	MAX_PRIORITY; //线程具有的最高优先级,值为10
static int	MIN_PRIORITY;//线程可以具有的最低优先级,值为1
static int	NORM_PRIORITY; //线程的默认优先级,值为5

  一个线程中的子线程的初始优先级与父线程相同,可以调用setPriority()方法设置线程的优先级,也可以通过getPriority()方法得到线程的优先级。

public class ThreadPriority extends Thread{
	public ThreadPriority(String str){
		super(str);
	}
	int count=0;
	int num=0;
	public void run(){
		for(int i=0;i<10000;i++){
			count++;
			for(int j=0;j<10000000;j++){
				num++;
			}
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadPriority t1 = new ThreadPriority("Iphone");
		t1.setPriority(MAX_PRIORITY);
		ThreadPriority t2 = new ThreadPriority("Huawei");
		t2.setPriority(NORM_PRIORITY);
		ThreadPriority t3 = new ThreadPriority("Meizu");
		t3.setPriority(MIN_PRIORITY);
		System.out.println(t1.getName()+"优先级:"+t1.getPriority());
		System.out.println(t2.getName()+"优先级:"+t2.getPriority());
		System.out.println(t3.getName()+"优先级:"+t3.getPriority());
		t1.start();
		t2.start();
		t3.start();
		try{
			Thread.sleep(500);
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println(t1.getName()+":"+t1.count+" "+t2.getName()+":"+t2.count+" "+t3.getName()+":"+t3.count);
	}
}

  运行结果为:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值