在Java中,每个线程都有一个优先级,默认是一个线程继承它的父线程的优先级。一个线程的默认优先级为NORM_PRIORITY = 5java
设置优先级的方法setPriority() ,可设置的值以下: ide
1
2
3
|
static
int
MAX_PRIORITY =
10
;
//线程能够具备的最高优先级(执行几率最高)
static
int
MIN_PRIORITY =
1
;
//线程能够具备的最低优先级(执行几率最低)
static
int
NORM_PRIORITY =
5
;
//分配给线程的默认优先级
|
线程的优先级:不是说哪一个线程优先执行,若是设置某个线程的优先级高。那就是有可能被执行的几率高。并非优先执行
测试
线程优先级实例代码:这里设置线程1为最高优先级(被执行的几率高) 设置线程2为最低优先级this
这里设置了线程1最高和线程2最低优先级后,并非说线程1就优先执行等到线程1执行完才执行线程2。而是说线程1被执行的几率高。spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//线程类
public
class
PriorityThread
implements
Runnable{
private
boolean
flag =
true
;
private
int
num=
0
;
@Override
public
void
run() {
while
(flag){
System.out.println(Thread.currentThread().getName()+
"-->"
+num++);
}
}
public
void
stop(){
this
.flag = !
this
.flag;
}
}
//测试线程优先级
public
class
PriorityDemo {
public
static
void
main(String[] args)
throws
InterruptedException {
PriorityThread it1 =
new
PriorityThread();
PriorityThread it2 =
new
PriorityThread();
Thread proxy1 =
new
Thread(it1,
"线程1"
);
Thread proxy2 =
new
Thread(it2,
"线程2"
);
proxy1.setPriority(Thread.MAX_PRIORITY);
//设置为最高优先级
proxy2.setPriority(Thread.MIN_PRIORITY);
//设置为最低优先级
proxy1.start();
proxy2.start();
Thread.sleep(
1000
);
it1.stop();
it2.stop();
}
}
|
执行结果以下:线程
线程1-->47755 统计共执行了4685次code
线程2-->19211 统计共执行了1469次继承
一、每一个线程都有一个默认的优先级,默认状况下是NORM_PRIORITY = 5ci
二、线程的优先级表示的是被执行的几率,并非绝对的优先执行。get
三、设置线程优先级的方法setPriority(Thread.MAX_PRIORITY);