- CPU 优先执行优先级较高的线程对象中的任务。
- 设置线程的优先级使用 setPriority() 方法。
- JDK 中常使用三个预定义的常量来控制线程的优先级
-
-
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
-
- 线程的优先级一共划分为 1 ~ 10 的十个等级,如果小于 1 或者大于 10 的情况下,JDK 会抛出异常 throw new IllegalArgumentException()。
- 线程的优先级有继承性、规则性、随机性。
- 守护线程即是一种特殊的线程 ( Daemon ) ,当进程中不存在用户线程后,则守护线程即会自动销毁。java 的垃圾回收线程也是守护线程之一。
- 用户也可以自行设置自身的某一线程为守护线程 , Thread.setDeamon(true);
class ThreadA extends Thread{
private int i =0;
@Override
public void run(){
try{
while(true){
i++;
System.out.println("i=" + i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class test1{
public static void main(String[] args){
Thread a = new ThreadA();
a.setDaemon(true);
a.start();
try{
a.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print("停止之后,守护线程再也无法进行打印");
}
}
i=1
i=2
i=3
i=4
i=5
停止之后,守护线程再也无法进行打印
- yield() 函数的作用是放弃当前的 CPU 资源,但是放弃的时间并不确定。
class ThreadA extends Thread{
@Override
public void run(){
long begin = System.currentTimeMillis();
int count = 0;
for(int i = 0; i < 1000000; i++){
Thread.yield();
count = count+i;
}
long end = System.currentTimeMillis();
System.out.print("总耗时" + (end - begin));
}
}
public class test0{
public static void main(String[] args){
Thread a = new ThreadA();
a.start();
}
}
注释掉:Thread.yield();
总耗时3
不注释
总耗时670

被折叠的 条评论
为什么被折叠?



