ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Thread中一些简单的API ```java /** * @program: ThreadDemo * @description: Thread中一些简单的API * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class ThreadSimpleAPI { public static void main(String[] args) { Thread t1 = new Thread(() -> { Optional.of("Hello").ifPresent(System.out::println); try { Thread.sleep(1_000); } catch (InterruptedException e) { e.printStackTrace(); } }, "t1"); t1.start(); // 线程名称。 Optional.of(t1.getName()).ifPresent(System.out::println); // 线程ID。++threadSeqNumber Optional.of(t1.getId()).ifPresent(System.out::println); // 线程优先级,默认为5. Optional.of(t1.getPriority()).ifPresent(System.out::println); } } ``` 很简单的api运行效果如下: ![](https://img.kancloud.cn/6e/29/6e294b1f5aa9662d98e10cf02410bc4e_960x638.gif) 接下来再通过代码来验证:*线程不一定会按照指定的优先级执行*。 ```java import java.util.Optional; /** * @program: ThreadDemo * @description: 线程优先级:验证:线程不一定会按照指定的优先级执行。 * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class ThreadSimpleAPI2 { public static void main(String[] args) { Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { Optional.of(Thread.currentThread().getName() + "-Index-" + i).ifPresent(System.out::println); } }, "t1"); t1.setPriority(Thread.MAX_PRIORITY); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { Optional.of(Thread.currentThread().getName() + "-Index-" + i).ifPresent(System.out::println); } }, "t2"); t2.setPriority(Thread.NORM_PRIORITY); Thread t3 = new Thread(() -> { for (int i = 0; i < 1000; i++) { Optional.of(Thread.currentThread().getName() + "-Index-" + i).ifPresent(System.out::println); } }, "t3"); t3.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); t3.start(); } } ``` 运行结果如下: ![](https://img.kancloud.cn/93/1a/931a2ae92d7bb4e239b0a3b1c6e418bb_575x387.png) 可以看到他们是交替执行的,所以线程的优先级我们应该在逻辑上去实现。这里就做个了解。