概述
使用方法
getState()
setPriority(Thread.MAX_PRIORITY);
实例
状态
/**
* 线程状态
* new -》 runnable -》 TIMED_WAITING -》 TERMINATED
*/
public class ThreadState {
public static void main(String[] args) {
Thread t1 = new Thread(()-> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/////////////////");
});
Thread.State state = t1.getState();
System.out.println(state); //new
t1.start();
state = t1.getState();
System.out.println(state); //run
while (state != Thread.State.TERMINATED){
try {
Thread.sleep(1000);
state = t1.getState();
System.out.println(state);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
优先级
/**
* 线程优先级
*/
public class ThreadPriority {
public static void main(String[] args) {
// 主线程优先级
System.out.println(Thread.currentThread().getName()+"=====>>"+Thread.currentThread().getPriority());
Thread t1 = new Thread(new MyPriority());
Thread t2 = new Thread(new MyPriority());
Thread t3 = new Thread(new MyPriority());
Thread t4 = new Thread(new MyPriority());
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(3);
t3.setPriority(2);
t4.setPriority(1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"=====>>"+Thread.currentThread().getPriority());
}
守护线程
守护线程是指为其他线程服务的线程。在JVM中,所有非守护线程都执行完毕后,无论有没有守护线程,虚拟机都会自动退出。
因此,JVM退出时,不必关心守护线程是否已结束。
Thread t = new MyThread();
t.setDaemon(true);
t.start();