线程的优先级
-
Java提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
-
线程的优先级用数字表示,范围从1~~~10
- Thread.MIN_PRIORITY = 1;
- Thread.max_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
-
使用以下方式改变或获取优先级
- get Priority().set Priority(int xxx)
-
优先级的设定建议在start()调度之前。
-
优先级低的只是概率低而已,主要是看cpu调度。
package com.jia.state;
//测试线程的优先级
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
//先设置优先级。再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
// t5.setPriority(-1);
// t5.start();
// t6.setPriority(12);
// t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如,后台记录操作日志,监控内存,垃圾回收等待
package com.jia.state;
//测试守护线程
//祖国守护你
public class TestDaemon {
public static void main(String[] args) {
Motherland motherland = new Motherland();
You you = new You();
Thread thread = new Thread(motherland);
thread.setDaemon(true);//默认是false表示用户线程,正常的线程都是用户线程。。。
thread.start();//祖国永远守护着你
new Thread(you).start();//你 用户线程启动
}
}
//祖国
class Motherland implements Runnable{
@Override
public void run() {
while(true){
System.out.println("祖国一直保护着你!");
}
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 40000; i++) {
System.out.println("你一生都活的很开心");
}
System.out.println("========祝君今日飞升!========");
}
}