线程状态
Thread.state
New | 尚未启动的线程处于此状态 |
---|---|
Runnable | 在java虚拟机中执行的线程处于此状态 |
Blocked | 被阻塞等待监视器锁定的线程处于此状态 |
Waiting | 正在等待另一个线程执行特定动作的线程处于此状态 |
Time_Waiting | 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态 |
Terminated | 已退出的线程处于此状态 |
package Thread;
/**
* @author zxy
* 观察测试线程的状态
*
*/
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for(int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("");
});
/* 观察状态 */
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);
}
}
}
输出:
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
·········
TIMED_WAITING
TERMINATED
线程优先级
- java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
- 线程的优先级用数字表示,范围从1-10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
- 使用以下方式改变或获取优先级:
- getPriority().setPriority(int xxx)
- 优先级的设定建议在start调度前
- 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度
package Thread;
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);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
/* 先设置优先级 再启动start方法 */
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(Thread.MAX_PRIORITY);
t3.start();
t4.setPriority(8);
t4.start();
t5.setPriority(Thread.MAX_PRIORITY);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+
"-->"+Thread.currentThread().getPriority());
}
}
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如 后台记录操作日志、监控内存、垃圾回收等待