
Thread.state
package Thread;
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);
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());
}
}
守护线程
线程分为用户线程和守护线程虚拟机必须确保用户线程执行完毕虚拟机不用等待守护线程执行完毕如 后台记录 *** 作日志、监控内存、垃圾回收等待
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)