0
点赞
收藏
分享

微信扫一扫

Java Thread类的yield()和join()的区别和用法

云卷云舒xj 2022-12-06 阅读 195


yield:

解释它之前,先简述下,多线程的执行流程:多个线程并发请求执行时,由cpu决定优先执行哪一个,即使通过thread.setPriority(),设置了

线程的优先级,也不一定就是每次都先执行它

yield,表示暂停当前线程,执行其他线程(包括自身线程) 由cpu决定



1. public class TestYield implements Runnable {  
2.
3. public void run() {
4. for (int i = 1; i <= 15; i++) {
5. ": " + i);
6. // 暂停当前正在执行的线程对象,并执行其他线程,就是进入就绪状态
7. Thread.currentThread().yield();
8. // 可能还会执行本线程,
9. }
10. }
11.
12. public static void main(String[] args) {
13. new TestYield();
14. newrunnable );
15. newrunnable );
16. newrunnable );
17.
18. 1);
19. t1.start();
20. t2.start();
21. t3.start();
22.
23. }
24. }


join:

阻塞所在线程,等调用它的线程执行完毕,再向下执行


1. public static void main(String[] args) throws InterruptedException {  
2.
3. final Thread thread1 = new Thread() {
4. public void run() {
5. "我是第一个");
6. try {
7. 500);
8. catch (InterruptedException e) {
9. e.printStackTrace();
10. }
11. "我虽然睡了一会,但我是第二个");
12. };
13. };
14. thread1.start();
15. //在这阻塞主线程
16. new Thread() {
17. public void run() {
18. try {
19. thread1.join();
20. catch (InterruptedException e) {
21. e.printStackTrace();
22. // 等待t1线程 执行完结,才继续向下执行 在这阻塞子线程
23. "我是第三个");
24. };
25. };
26. thread2.start();
27. }

举报

相关推荐

0 条评论