本教程将讲解“如何在Java中设置线程的优先级”。每个线程都有一个优先级,优先级代表从 1 到 10 的整数。
使用setPriority([[$2$]])
方法可以设置线程的优先级,使用getPriority()
方法可以查看线程的优先级。
Thread 类提供 3 个恒定优先级
MIN_PRIORITY
– 设置线程的最小优先级,即1NORM_PRIORITY
–设置线程的正常优先级,即5MAX_PRIORITY
–设置线程的最大优先级,即10由于我们知道优先级表示从 1 到 10 的整数,我们可以设置线程的 custom or user-defined priority
。
CUST_PRIORITY
– 设置线程的自定义优先级。int CUST_PRIORITY = 7;
setPriority(CUST_PRIORITY);
//or
setPriority(7);
投掷:IllegalArgumentException
如果优先级不在 MIN_PRIORITY
到 MAX_PRIORITY
的范围内,并且SecurityException
如果当前线程不能修改这个线程。
注意: 首先不带参数调用该线程的 checkAccess
方法。确定当前运行的线程是否有权修改此线程。
MinPriorityThreadExp.java
package org.websparrow.thread.methods;
public class MinPriorityThreadExp extends Thread {
@Override
public void run() {
Thread thread = new Thread();
thread.checkAccess();
thread.setPriority(MIN_PRIORITY);
System.out.println("Priority of thread is : " + thread.getPriority());
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException {
MinPriorityThreadExp minPriority = new MinPriorityThreadExp();
minPriority.start();
}
}
输出:
Priority of thread is : 1
NormPriorityThreadExp.java
package org.websparrow.thread.methods;
public class NormPriorityThreadExp extends Thread {
@Override
public void run() {
Thread thread = new Thread();
thread.checkAccess();
thread.setPriority(NORM_PRIORITY);
System.out.println("Priority of thread is : " + thread.getPriority());
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException {
NormPriorityThreadExp normPriority = new NormPriorityThreadExp();
normPriority.start();
}
}
输出:
Priority of thread is : 5
MaxPriorityThreadExp.java
package org.websparrow.thread.methods;
public class MaxPriorityThreadExp extends Thread {
@Override
public void run() {
Thread thread = new Thread();
thread.checkAccess();
thread.setPriority(MAX_PRIORITY);
System.out.println("Priority of thread is : " + thread.getPriority());
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException {
MaxPriorityThreadExp maxPriority = new MaxPriorityThreadExp();
maxPriority.start();
}
}
输出:
Priority of thread is : 10
CustPriortyThreadExp.java
package org.websparrow.thread.methods;
public class CustPriortyThreadExp extends Thread {
@Override
public void run() {
int CUST_PRIORITY = 7;
Thread thread = new Thread();
thread.checkAccess();
thread.setPriority(CUST_PRIORITY);
// or you can directly set the priority setPriority(7)
System.out.println("Priority of thread is : " + thread.getPriority());
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException {
CustPriortyThreadExp custPriority = new CustPriortyThreadExp();
custPriority.start();
}
}
输出:
Priority of thread is : 7
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/how-to-set-thread-priority-in-java
内容来源于网络,如有侵权,请联系作者删除!