观测线程状态,守护(daemon)线程
观测线程状态
package com.Jinone.www;
public class TextState {
public static void main(String[] args) {
Thread thread=new Thread(()->{
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/");
});
Thread.State state=thread.getState();
System.out.println(state);
thread.start();
state=thread.getState();
System.out.println(state);
while(state!=Thread.State.TERMINATED) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state=thread.getState();
System.out.println(state);
}
thread.start();
}
}
守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如,后台记录操作日志,监控内存,垃圾回收等待…
package com.Jinone.www;
public class TextDaemon {
public static void main(String[] args) {
God god=new God();
You you=new You();
Thread thread=new Thread(god);
thread.setDaemon(true);
thread.start();
new Thread(you).start();
}
}
class God implements Runnable{
@Override
public void run() {
while(true) {
System.out.println("上帝保佑着你");
}
}
}
class You implements Runnable{
@Override
public void run() {
for(int i=0;i<36500;i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("====你死了====");
}
}