public class CustomThread extends Thread {
public void run(){
IntStream.range(0, 3).parallel().forEachOrdered(x -> System.out.println("Child Thread :- "+Thread.currentThread().getName()+"-"+x));
}
}
public class CustomThreadDemo {
public static void main(String[] args) {
CustomThread customThread = new CustomThread();
customThread.setPriority(Thread.MIN_PRIORITY);
customThread.setName("CustomThread");
customThread.start();
CustomThread customThread1 = new CustomThread();
customThread1.setPriority(Thread.MAX_PRIORITY);
customThread1.setName("CustomThread1");
customThread1.start();
IntStream.range(0, 3).parallel().forEachOrdered(x ->
System.out.println("Parent Thread :- "+x));
}
}
默认情况下,两个线程具有相同的优先级(5),这就是为什么我们不能期望正确的排序结果,但是如果我们设置子线程优先级 - Thread-Scheduler将如何执行。
答案 0 :(得分:0)
虽然调度程序应该优先选择具有更高优先级的线程,但是依赖于任何行为都不能保存。使用synchronized块和其他机制来确保线程安全,如
中所定义https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html