线程的优先级
-
MAX_PRIORITY:10
-
MIN_PRIORITY:1
-
如何获取和设置当前线程的优先级:
不修改getPriority():
package new1;
public class demo2 {
public static void main(String[] args) {
MyThread3 h1 = new MyThread3();
h1.setName("线程一");
h1.start();
//给主线程命名
Thread.currentThread().setName("主线程");
for (int i = 0; i < 20; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
}
}
System.out.println(h1.isAlive());
}
}
class MyThread3 extends Thread {
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
//可以写成System.out.println(getName()+":"+getPriority()+":"+i);
}
}
}
}
运行结果
主线程:5:1
主线程:5:3
主线程:5:5
主线程:5:7
主线程:5:9
线程一:5:0
线程一:5:2
线程一:5:4
线程一:5:6
线程一:5:8
线程一:5:10
线程一:5:12
线程一:5:14
线程一:5:16
线程一:5:18
主线程:5:11
主线程:5:13
主线程:5:15
主线程:5:17
主线程:5:19
false
设置优先级
package new1;
public class demo2 {
public static void main(String[] args) {
MyThread3 h1 = new MyThread3();
h1.setName("线程一");
//设置分线程的优先级
h1.setPriority(Thread.MAX_PRIORITY);
h1.start();
//给主线程命名
Thread.currentThread().setName("主线程");
//设置主线程的优先级
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
for (int i = 0; i < 20; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
}
}
System.out.println(h1.isAlive());
}
}
class MyThread3 extends Thread {
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
//可以写成System.out.println(getName()+":"+getPriority()+":"+i);
}
}
}
}
结果
主线程:1:1
线程一:10:0
主线程:1:3
主线程:1:5
主线程:1:7
主线程:1:9
主线程:1:11
线程一:10:2
线程一:10:4
线程一:10:6
线程一:10:8
线程一:10:10
线程一:10:12
线程一:10:14
线程一:10:16
线程一:10:18
主线程:1:13
主线程:1:15
主线程:1:17
主线程:1:19
false
很明显高优先级不一定第一个全输出完,只是概率增加了