Thread中一些简单的API
Thread中一些简单的API
/**
* @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运行效果如下:

接下来再通过代码来验证:线程不一定会按照指定的优先级执行。
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();
}
}
运行结果如下:

可以看到他们是交替执行的,所以线程的优先级我们应该在逻辑上去实现。这里就做个了解。

浙公网安备 33010602011771号