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

yield:

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

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

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

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

join:

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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值