【学习笔记】线程(五)线程优先级、守护线程
线程优先级
-
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按学号优先级决定应该调度哪个线程来执行。
-
-
Thread.MIN_PRIORITY = 1;
-
Thread.MAX_PRIORITY = 10;
-
Thread.NORM_PRIORITY = 5; //默认优先级,不设置的话就是默认优先级
-
-
线程优先级高不一定先执行,但是给它的资源就会多一些
-
使用以下方式来改变或获取优先级
-
getPriority() //获取优先级
-
setPriority(int xxx) //改变优先级
-
package com.thread.demo03;
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,"t1");
Thread t2 = new Thread(myPriority,"t2");
Thread t3 = new Thread(myPriority,"t3");
Thread t4 = new Thread(myPriority,"t4");
//设置优先级并启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(6);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY); //MAX_PRIORITY = 10
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
}
}
从运行结果我们可以看出,即使t3 的优先级比t1高,也没有先执行
所以 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU 的调度
优先级的设置建议在start()调度前
守护线程
-
线程分为用户线程和守护线程
-
虚拟机必须确保用户线程执行完毕
-
虚拟机不用等待守护线程执行完毕
-
守护线程:后台记录操作日志,监控内存,垃圾回收等待
通过 setDaemon(true) 方法来设置守护线程,参数为true是守护线程,默认是false用户线程
package com.thread.demo03;
public class TestDaemon {
public static void main(String[] args) {
User user = new User();
Guard guard = new Guard();
Thread thread = new Thread(guard);
thread.setDaemon(true); //默认是false,即用户线程,true为守护线程
thread.start();
new Thread(user).start();
}
}
//用户线程
class User implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("用户线程正在运行");
}
System.out.println("用户线程结束了");
}
}
//守护线程
class Guard implements Runnable{
@Override
public void run() {
while (true) {
System.out.println("守护线程正在运行");
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!