首页 > 代码库 > 多线程-3

多线程-3

三、线程优先级

1.关于线程的优先级:
/**
* 如何获取线程对象的优先级?
* public final int getPriority():返回线程对象的优先级
* 如何设置线程对象的优先级呢?
* public final void setPriority(int newPriority):更改线程的优先级。
*
* 注意:
* 线程默认优先级是5。
* 线程优先级的范围是:1-10。
* 线程优先级高仅仅表示线程获取的 CPU时间片的几率高,但是要在次数比较多,或者多次运行的时候才能看到比较好的效果。
*
* IllegalArgumentException:非法参数异常。
* 抛出的异常表明向方法传递了一个不合法或不正确的参数。
*
*/

实例代码:
public class Thread3 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程:" + getName() + " : " + i);
}
}
}

public static void main(String[] args) {
Thread3 th1 = new Thread3();
Thread3 th2 = new Thread3();
Thread3 th3 = new Thread3();

th1.setName("初音未来");
th2.setName("鬼泣");
th3.setName("妖姬");

th2.setPriority(1);

th1.start();
th2.start();
th3.start();
}
}

多线程-3