public class Test_sleep_yield_join {
public static void main(String[] args) {
// testSleep();
testYield();
}
static void testSleep(){
// 使用Lamda 表达式测试
new Thread(()->{
for(int i=0;i<100;i++){
System.out.println("sleep "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
static void testYield(){
new Thread(()->{
for(int i=0;i<100;i++){
System.out.println("yield A "+i);
if(i%10==0){
Thread.yield();
}
}
}).start();
new Thread(()->{
for(int i=0;i<100;i++){
System.out.println("yield B "+i);
if(i%10==0){
Thread.yield();
}
}
}).start();
}
static void testJoin(){
Thread t1 = new Thread(()->{
for(int i=0;i<10;i++){
System.out.println("join t1 "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(()->{
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<10;i++){
System.out.println("join t2 "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
2021-07-11- java 线程 Sleep, yield, join 实例代码
本文详细介绍了Java中的testSleep()、testYield()和testJoin()方法,展示了如何使用Thread.sleep()实现睡眠,Thread.yield()进行任务让步,以及Thread.join()实现线程同步。通过实例演示了这些并发控制手段在实际编程中的作用。
339

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



