如何在Java中设置线程优先级

x33g5p2x  于2021-10-26 转载在 Java  
字(2.5k)|赞(0)|评价(0)|浏览(423)

本教程将讲解“如何在Java中设置线程的优先级”。每个线程都有一个优先级,优先级代表从 1 到 10 的整数。

使用setPriority([[$2$]])方法可以设置线程的优先级,使用getPriority()方法可以查看线程的优先级。

Thread 类提供 3 个恒定优先级

  1. MIN_PRIORITY– 设置线程的最小优先级,即1
  2. NORM_PRIORITY–设置线程的正常优先级,即5
  3. MAX_PRIORITY–设置线程的最大优先级,即10

由于我们知道优先级表示从 1 到 10 的整数,我们可以设置线程的 custom or user-defined priority

  • CUST_PRIORITY– 设置线程的自定义优先级。

定义自定义优先级

int CUST_PRIORITY = 7;
setPriority(CUST_PRIORITY);
//or
setPriority(7);

投掷:
IllegalArgumentException 如果优先级不在 MIN_PRIORITYMAX_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

相关文章

微信公众号

最新文章

更多