多线程优先级——Priority

线程的优先级1-10

  • 1.NORM_PRIORITY 5 默认
  • 2.MIN_PRIORITY 1
  • 3.MAX_PRIORITY 10
  • 概率,不代表绝对的先后顺序,也就是说优先级为10的并不一定就比优先级为1的先运行,只是它先运行的概率比优先级为1的大,优先级为1-10,不能超过这个范围。
  • 一般默认优先级为5.
package thread.lzy.www;
/**
 * 线程的优先级1-10
 * 1.NORM_PRIORITY 5 默认
 * 2.MIN_PRIORITY 1
 * 3.MAX_PRIORITY
 * 概率,不代表绝对的先后顺序
 * @author Administration
 *
 */
public class eProrityTest {

	public static void main(String[] args) {
		System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
		 MyPriority mp=new  MyPriority();
		Thread t1=new Thread(mp,"a");
		Thread t2=new Thread(mp,"b");
		Thread t3=new Thread(mp,"c");
		Thread t4=new Thread(mp,"d");
		Thread t5=new Thread(mp,"e");
		Thread t6=new Thread(mp,"f");
		//设置优先级在启动前
		t1.setPriority(Thread.MAX_PRIORITY);//t1.setPriority(10);也可以直接写数字1-10都可
		t2.setPriority(Thread.MAX_PRIORITY);
		t3.setPriority(Thread.MAX_PRIORITY);
		t4.setPriority(Thread.MIN_PRIORITY);
		t5.setPriority(Thread.MIN_PRIORITY);
		t6.setPriority(Thread.MIN_PRIORITY);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		 
	}
}
class MyPriority implements Runnable{

	@Override
	public void run() {
		
		System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
	}
	
}

代码中a,b,c的优先级为10。d,e,f的优先级为1,但真的就是a,b,c先运行吗 ,答案不是的,
某次运行结果:
main–>5
a–>10
b–>10
e–>1
c–>10
d–>1
f–>1
可以看出c虽然优先级高于e,但并没有先运行,只是它的概率高而已


版权声明:本文为weixin_44805105原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。