通过线程获取name,id,priority
public class ThreadApi {
public static void main(String[] args) {
Thread t = new Thread(()->{
Optional.of("hello").ifPresent(System.out::println);
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
},"testThread");
t.start();
Optional.of(t.getName()).ifPresent(System.out::println);
Optional.of(t.getId()).ifPresent(System.out::println);
Optional.of(t.getPriority()).ifPresent(System.out::println);
}
}
得到的线程的名称是我赋值的testThread
得到线程的id是11,这说明在启动该线程前,jvm创建了多个其他的线程,我们可以通过jconsole查看
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d7205cd2591708e950c37e87f4281317.jpeg)
线程默认优先级是5
注意,线程的优先级并不代表执行顺序的先后
public class ThreadApi2 {
public static void main(String[] args) {
Thread t0 = new Thread(()->{
for (int i =0;i<100;i++) {
Optional.of(Thread.currentThread().getName()+"-index:"+i).ifPresent(System.out::println);
}
});
t0.setPriority(Thread.MAX_PRIORITY);
Thread t1 = new Thread(()->{
for (int i =0;i<100;i++) {
Optional.of(Thread.currentThread().getName()+"-index:"+i).ifPresent(System.out::println);
}
});
t1.setPriority(Thread.NORM_PRIORITY);
Thread t2 = new Thread(()->{
for (int i =0;i<100;i++) {
Optional.of(Thread.currentThread().getName()+"-index:"+i).ifPresent(System.out::println);
}
});
t2.setPriority(Thread.MIN_PRIORITY);
t0.start();
t1.start();
t2.start();
}
}
我创建了3个线程t0、t1、t2优先级分别是10、5、1,但是先执行的却是t2,由此可知线程的优先级高的未必是先被执行的.