java设置线程的优先级,java线程优先级,如果线程要执行的任务很紧
分享于 点击 30605 次 点评:280
java设置线程的优先级,java线程优先级,如果线程要执行的任务很紧
如果线程要执行的任务很紧急,这时候设置线程的优先级就是很重要的。
Thread类有setPriority(int level)方法用来设置线程的优先级。
线程的有限级从1到10,1是最不重要的,10是最重要的。如果没有给线程设置优先级,那么线程的优先级将是默认值5.
下面第一个例子代码展示未设置优先级情况下的输出,
/** * Main.java * * @author byrx.net */public class Main { /** * Starts two threads and wait for them to finish. */ public void setPrioritiesOnThreads() { Thread thread1 = new Thread(new TestThread(1)); Thread thread2 = new Thread(new TestThread(2)); thread1.start(); thread2.start(); try { //Wait for the threads to finish thread1.join(); thread2.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Done."); } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().setPrioritiesOnThreads(); } class TestThread implements Runnable { int id; public TestThread(int id) { this.id = id; } public void run() { for (int i = 1; i <= 10; i++) { System.out.println("Thread" + id + ": " + i); } } }}
因为两个线程的优先级是一样的所以,两个线程交叉执行
Thread2: 1Thread1: 1Thread2: 2Thread1: 2Thread2: 3Thread1: 3Thread2: 4Thread1: 4Thread2: 5Thread1: 5Thread2: 6Thread1: 6Thread2: 7Thread2: 8Thread2: 9Thread2: 10Thread1: 7Thread1: 8Thread1: 9Thread1: 10Done.
如果我们设置了线程的优先级,CPU就会优先给优先级高的线程,如下代码:
/** * Main.java * * @author byrx.net */public class Main { /** * Starts two threads, setting priorities on them * and wait for them to finish. * */ public void setPrioritiesOnThreads() { Thread thread1 = new Thread(new TestThread(1)); Thread thread2 = new Thread(new TestThread(2)); //Setting priorities on the Thread objects thread1.setPriority(Thread.MAX_PRIORITY); thread2.setPriority(Thread.MIN_PRIORITY); thread1.start(); thread2.start(); try { //Wait for the threads to finish thread1.join(); thread2.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Done."); } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().setPrioritiesOnThreads(); } class TestThread implements Runnable { int id; public TestThread(int id) { this.id = id; } public void run() { for (int i = 1; i <= 10; i++) { System.out.println("Thread" + id + ": " + i); } } }}
输出如下:
Thread1: 1Thread1: 2Thread1: 3Thread1: 4Thread1: 5Thread1: 6Thread1: 7Thread1: 8Thread1: 9Thread1: 10Thread2: 1Thread2: 2Thread2: 3Thread2: 4Thread2: 5Thread2: 6Thread2: 7Thread2: 8Thread2: 9Thread2: 10Done.
用户点评