只有使用 join 方法能够保证线程执行的先后顺序,对线程设置优先级并不能够保证 其先后顺序,仅仅式优先级高的thread 获取cpu资源的概率大一些罢了;
如有错误 望大家指出,共同学习。
public class ThreadPriority {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程1执行");
}
});
thread1.setName("线程1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程2执行");
}
});
thread2.setName("线程2");
// 设置线程的优先级
// thread1.setPriority(1);
// thread2.setPriority(2);//先执行
thread1.start();
thread1.join();
thread2.start();
thread2.join();
}
}
多次测试执行结果为: