java后台进程和线程优先级
1. 后台线程:处于后台运行,任务是为其他线程提供服务。也称为“守护线程”或“精灵线程”。JVM的垃圾回收就是典型的后台线程。
特点:若所有的前台线程都死亡,后台线程自动死亡。
设置后台线程:Thread对象setDaemon(true);
setDaemon(true)必须在start()调用前。否则出现IllegalThreadStateException异常;
前台线程创建的线程默认是前台线程;
判断是否是后台线程:使用Thread对象的isDaemon()方法;
并且当且仅当创建线程是后台线程时,新线程才是后台线程。
例子:
class Daemon implements Runnable{
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("Daemon -->" + i);
}
}
}
public class DaemonDemo {
public static void main(String[] args) {
/*Thread cThread = Thread.currentThread();
System.out.println(cThread.isAlive());
//cThread.setDaemon(true);
System.out.println(cThread.isDaemon());*/
Thread t = new Thread(new Daemon());
System.out.println(t.isDaemon());
for (int i = 0; i < 10; i++) {
System.out.println("main--" + i);
if(i == 5){
t.setDaemon(true);
t.start();
}
}
}
}
2,线程的优先级:
每个线程都有优先级,优先级的高低只和线程获得执行机会的次数多少有关。
并非线程优先级越高的就一定先执行,哪个线程的先运行取决于CPU的调度;
默认情况下main线程具有普通的优先级,而它创建的线程也具有普通优先级。
Thread对象的setPriority(int x)和getPriority()来设置和获得优先级。
MAX_PRIORITY :值是10
MIN_PRIORITY :值是1
NORM_PRIORITY :值是5(主方法默认优先级)
注意:每个线程默认的优先级都与创建他的父线程的优先级相同,在在默认的情况下,
main线程具有普通优先级,由main线程创建的子线程也具有普通优先级
例子:
class Priority implements Runnable{
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("Priority-- " + i);
}
}
}
public class PriorityDemo {
public static void main(String[] args) {
/**
* 线程的优先级在[1,10]之间
*/
Thread.currentThread().setPriority(3);
System.out.println("main= " + Thread.currentThread().getPriority());
/*
* public final static int MIN_PRIORITY = 1;
* public final static int NORM_PRIORITY = 5;
* public final static int MAX_PRIORITY = 10;
* */
System.out.println(Thread.MAX_PRIORITY);
//===============================================
Thread t = new Thread(new Priority());
for (int i = 0; i < 200; i++) {
System.out.println("main" + i);
if(i == 50){
t.start();
t.setPriority(10);
}
System.out.println("-------------------------"+t.getPriority());
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架