版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40285302/article/details/85853223
package com.thread;
public class TestPriority {
public static void main(String[] args) {
PriorityThread pt = new PriorityThread();
ThreadGroup tg1 = new ThreadGroup("线程1组");
ThreadGroup tg2 = new ThreadGroup("线程2组");
Thread t1 = new Thread(tg1, pt, "线程1");
Thread t2 = new Thread(tg1, pt, "线程2");
Thread t3 = new Thread(tg2, pt, "线程3");
Thread t4 = new Thread(tg2, pt, "线程4");
t1.setPriority(11);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t4.setPriority(Thread.MAX_PRIORITY);
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
System.out.println(t4);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class PriorityThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"-----"+i);
}
}
}
在为线程设置优先级的时候,有两种设置方法。
一种是数字式:
t1.setPriority(10);
括号中间的数字只能是1-10。如果小于1或者大于10,都会报错:Exception in thread "main" java.lang.IllegalArgumentException。
对应的源码如下:
/**
* Changes the priority of this thread.
* <p>
* First the <code>checkAccess</code> method of this thread is called
* with no arguments. This may result in throwing a
* <code>SecurityException</code>.
* <p>
* Otherwise, the priority of this thread is set to the smaller of
* the specified <code>newPriority</code> and the maximum permitted
* priority of the thread's thread group.
*
* @param newPriority priority to set this thread to
* @exception IllegalArgumentException If the priority is not in the
* range <code>MIN_PRIORITY</code> to
* <code>MAX_PRIORITY</code>.
* @exception SecurityException if the current thread cannot modify
* this thread.
* @see #getPriority
* @see #checkAccess()
* @see #getThreadGroup()
* @see #MAX_PRIORITY
* @see #MIN_PRIORITY
* @see ThreadGroup#getMaxPriority()
*/
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
另一种方法是:
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t4.setPriority(Thread.NORM_PRIORITY);
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
主线程默认的优先级是NORM_PRIORITY,也就是5。如果一个线程没有设置优先级,则为默认的优先级。