public class TestState implements Runnable{
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("现在是第"+i+"个");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
TestState testState = new TestState();
Thread thread = new Thread(testState);
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);//run
while(state!= Thread.State.TERMINATED){//只要线程不停止,一直输出
thread.sleep(100);
state = thread.getState();
System.out.println(state);//输出状态
}
}
}
守护线程
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕,但不用等待守护线程执行完毕,如后台记录操作日志,监控内存,垃圾回收等待
//测试守护线程
//上帝守护你
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You;
Thread thread = new Thread(god);
thread.setDaemon(true);//默认是false是用户线程,正常线程都是用户线程
thread.start();//上帝守护线程启动
new Thread(new You()).start();
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("baohu");
}
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("live");
}
System.out.println("over");
}
}