MyPriority.java
public class MyPriority extends Thread{
public MyPriority(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(getName()+" "+i);
}
}
}
TestMyProprity.java
/*
* 设置和获取线程优先级
* public final int getPriority()
* public final void setPriority(int newPriority)
* 线程执行时随即的,并不是优先级越大就一定执行
*/
public class TestMyProprity {
public static void main(String[] args) {
//1.创建线程1对象
MyPriority myPriority1 = new MyPriority("Thread1");
//2.创建线程2对象
MyPriority myPriority2 = new MyPriority("Thread2");
//设置线程优先级,在线程启动前进行设置
//myPriority1.setPriority(1000); //java.lang.IllegalArgumentException
//线程优先级最大为10,最小为1
myPriority1.setPriority(10);//线程的优先级为10,但这仅仅说明抢到资源的概率最大,并不是一定抢到资源
myPriority2.setPriority(1);
//启动线程
myPriority1.start();
myPriority2.start();
}
}