线程Priority:
线程可以划分优先级,优先级较高的线程得到的CPU资源较多,也就是CPU优先执行优先级较高的线程对象中的任务。
设置线程优先级有助于帮助“线程规划器”确定在下一次选择哪个线程来优先执行。
线程优先级分为10个等级,1-》10
三个常用等级:
线程优先级继承性:
A线程启动了B线程,则B线程的优先级与A线程是一样的。
public class PriorityInheritThread extends Thread { @Override public void run() { System.out.println("1 Run priority = " + this.getPriority()); PriorityInheritThread2 thread2 = new PriorityInheritThread2(); thread2.start(); } } public class PriorityInheritThread2 extends Thread{ @Override public void run() { System.out.println("2 Run priority = " + this.getPriority()); } } public class ThreadRunMain { public static void main(String[] args) { testPriorityInheritThread(); } public static void testPriorityInheritThread() { System.out.println("Main thread begin priority = " + Thread.currentThread().getPriority()); Thread.currentThread().setPriority(6); System.out.println("Main thread end priority = " + Thread.currentThread().getPriority()); PriorityInheritThread thread1 = new PriorityInheritThread(); thread1.start(); } }
运行结果:
线程规则性:
优先级高的线程总是大部分先执行完。
线程随机性:
当线程优先等级差距很大,谁先执行完和Main线程代码的调用顺序无关。优先级高的线程也不一定每一次都先执行完。
public class RunFastThreadA extends Thread { private int count = 0; public int getCount() { return count; } @Override public void run() { while(true){ count ++; } } } public class RunFastThreadB extends Thread { private int count = 0; public int getCount() { return count; } @Override public void run() { while(true){ count ++; } } } public class ThreadRunMain { public static void main(String[] args) { testRunFastThread(); } public static void testRunFastThread() { try { RunFastThreadA a = new RunFastThreadA(); a.setPriority(Thread.NORM_PRIORITY - 3); a.start(); RunFastThreadB b = new RunFastThreadB(); b.setPriority(Thread.NORM_PRIORITY + 3); b.start(); Thread.sleep(10000); a.stop(); b.stop(); System.out.println("a = " + a.getCount()); System.out.println("b = " + b.getCount()); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果: