(1)Thread.sleep();
(2)Thread.yield();
概念:t1线程在运行,另外t2线程也在运行,当前t1线程在CPU上运行调用了一下yield(),从CPU先离开,另外t2线程可以在这执行。yield的t1进入等待队列中。本质是让出一下CPU,t2线程能否抢到进行执行t1不管。
(3)Thread.join();
概念:t1线程在运行,另外t2线程也在运行,t1的某一时刻调用了t2.join()。等待t2线程运行完毕,ti1再接着运行。
面试题:有3个线程如何保证有序执行完毕?
在main主程序中启动3个线程,分别为T1、T2、T3
T1.join();
T2.join();
T3join();
这样的执行顺序是T1>T2>T3
精确的是:
T1里边调用T2.join(),T2里边调用T3.join()。这样执行的顺序是T3>T2>T1
代码示例:
public class T03_Sleep_Yield_Join {
public static void main(String[] args) {
// testSleep();
// testYield();
testJoin();
}
static void testSleep() {
new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("A" + i);
try {
Thread.sleep(500);
//TimeUnit.Milliseconds.sleep(500)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
static void testYield() {
new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("A" + i);
if(i%10 == 0) Thread.yield();
}
}).start();
new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("------------B" + i);
if(i%10 == 0) Thread.yield();
}
}).start();
}
static void testJoin() {
Thread t1 = new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("A" + i);
try {
Thread.sleep(500);
//TimeUnit.Milliseconds.sleep(500)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(()->{
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0; i<100; i++) {
System.out.println("A" + i);
try {
Thread.sleep(500);
//TimeUnit.Milliseconds.sleep(500)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}

被折叠的 条评论
为什么被折叠?



