1、主线程A中执行子线程B中的start方法执行时,如果start方法后面没有调用B的join方法,则主线程A的优先级高于子线程B,会先于B执行,A执行完了之后在执行B;
如果start方法后面调用B的join方法,则子线程B会高于主线程而优先执行,执行完毕后才执行主线程。
package test;
/**
* 京东考题:加入什么始终会输出100
* @author USER
*
*/
class ms implements Runnable{
int i;
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i = 100;
System.out.println(i);
}
}
public class Test9 {
public static void main(String[] args) {
ms m = new ms();
Thread thread = new Thread(m);
thread.start();
//此处加入代码
/* try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//为了验证主线程在没有join方法时优先级高于子线程
for (int i = 0; i <10; i++) {
System.out.print(i+" ");
}
System.out.println();
int a=m.i;
System.out.println(a);
}
}
输出:
0 1 2 3 4 5 6 7 8 9
0
100
加入join方法后
100
0 1 2 3 4 5 6 7 8 9
100
2、sleep方法是让当前执行的线程暂停一段时间后继续执行,可以让高、低、同优先级的其他线程都有机会执行。
yield方法只能使同优先级的其他线程有机会执行,高、低优先级的其他线程都没有机会执行。