1.观测线程
JDK中定义的线程的六个状态 :
可以用getState()来观测线程
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(
()->{
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Thread is running " + i);
}
}
);
Thread.State state = thread.getState();
System.out.println("Thread state is " + state);
thread.start();
while(state!=Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();
System.out.println("Thread state is " + state);
}
}
观测结果:
线程一旦死亡(terminated状态),就不能再start()了
2.线程优先级
从低到高:1-10,一般默认为5
线程的优先级不能保证线程的执行顺序,因为具体调度策略是由OS决定的。
每当线程调度器有机会选择新线程时,它首先选择具有较高优先级的线程。但是,线程的优先级高度依赖于OS。
“当虚拟机依赖于宿主机平台的线程实现时,Java线程的优先级会映射到宿主平台的优先级,平台的线程优先级别可能比Java的10个级别多,也可能更少。
例如,Windows有7个优先级别。Java的一些优先级会映射到同一个操作系统优先级。在Oracle为Linux提供的Java虚拟机中,会完全忽略线程优先级————所有线程都具有相同的优先级。”
“线程优先级不能作为程序正确性的依赖,因为操作系统可以完全不用理会JAVA线程对于优先级的设定”
默认情况下,一个线程会继承构造它的那个线程的优先级。
在线程启动之前,设置优先级。
package oop;
public class D18 {
public static void main(String[] args) {
System.out.println("Thread " + Thread.currentThread().getName() + " Priority is " + Thread.currentThread().getPriority());
TestPriority testPriority = new TestPriority();
Thread thread = new Thread(testPriority);
Thread thread2 = new Thread(testPriority);
Thread thread3 = new Thread(testPriority);
Thread thread4 = new Thread(testPriority);
Thread thread5 = new Thread(testPriority);
thread.start();
thread2.setPriority(3);
thread2.start();
thread3.setPriority(10);
thread3.start();
thread4.setPriority(8);
thread4.start();
thread5.setPriority(9);
thread5.start();
}
}
class TestPriority implements Runnable{
@Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getName() + " Priority is " + Thread.currentThread().getPriority());
}
}
可以看到结果并不是完全按照线程优先级来执行的