惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
C
Check Point Blog
博客园_首页
B
Blog
D
Docker
U
Unit 42
量子位
I
InfoQ
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
GbyAI
GbyAI
L
LangChain Blog
云风的 BLOG
云风的 BLOG
博客园 - Franky
美团技术团队
T
The Blog of Author Tim Ferriss
阮一峰的网络日志
阮一峰的网络日志
月光博客
月光博客
Vercel News
Vercel News
Recent Announcements
Recent Announcements
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Google DeepMind News
Google DeepMind News

博客园 - 新一

HPUX 大文件系统扩容 LESS详解之函数(四) Win7 安装Apache 2.2.4报错:<OS 5>拒绝访问. :Failed to open the WinNT service manager 在Linux下用源码编译安装apache2 Java IO--压缩流 线程池技术 Red Hat dhclient [置顶] 开关电源的pcb设计规范 javascript 的一些理解和随笔 动态规划之 <筷子> 都是权限惹的祸! [LeetCode] Validate Binary Search Tree 解决IE6-IE8 Js代码不执行问题 linux下chmod使用 熬之滴水成石:最想深入了解的内容--windows内核机制(6) linux网络设备—PHY linux网络设备—mdio总线 通过action传过来的值在option获取进行验证 屌丝也用按位与(&),按位或(|) (二)
java后台进程和线程优先级
新一 · 2013-11-14 · via 博客园 - 新一


 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());
}
}
}