java多线程:5、Java对多线程的支持(二)线程优先级

版权声明:本文为博主原创文章,不得随意转载,转载请注明出处!!! https://blog.csdn.net/YuDBL/article/details/86088220

一、线程优先级

在java当中,每一个线程都有一个优先级,我们可以通过Thread当中的getPriority()方法、setPriority方法去得到一个线程的优先级和设置一个线程的优先级。 

设置线程优先级,它的参数是一个整形。最小为1(Thread.MIN_PRIORITY),缺省为5(Thread.NORM_PRIORITY),最高为10(Thread.MAX_PRIORITY)

并不一定要在线程start启动之前进行设置,我们在线程启动之后也可以设置修改线程的优先级。

t05_线程的优先级

MultiThread类

public class MultiThread {
	public static void main(String[] args) {
		MyThread mt = new MyThread();
		mt.setPriority(Thread.MAX_PRIORITY);//线程启动之前或之后设置都可以
		mt.start();
		
		int index = 0;
		while(true){
			
			if(index++ == 1000 )
					break;//到一千次就终止,跳出循环。 注意:if没有大括号
			
				System.out.println("main:"+Thread.currentThread().getName());
				
		}
		
	}
	
}

MyThread类

public class MyThread extends Thread {
	@Override
	public void run() {
		
		while(true){
			System.out.println(getName());
//			yield();//暂停当前线程,让其他线程执行
		} 
		
	}
}

在java当中如果某个线程优先级较高,那么他将始终获得优先运行的机会。

输出观察:

mt线程设置优先级    mt.setPriority(Thread.MAX_PRIORITY);   它始终获得优先运行的机会。

我们打开 yield()方法 的注释,即使运行设置了yield方法,它也始终会获得优先运行的机会。

一般只有可能在我们强制终止程序的时候,有可能会发现优先级较低的线程运行几次。

猜你喜欢

转载自blog.csdn.net/YuDBL/article/details/86088220
今日推荐