首页 技术 正文
技术 2022年11月21日
0 收藏 478 点赞 4,371 浏览 1202 个字

yield:

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

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

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

[java] view
plain
copyprint?

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

join:

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

[java] view
plain
copyprint?

  1. public static void main(String[] args) throws InterruptedException {
  2. final Thread thread1 = new Thread() {
  3. public void run() {
  4. System.out.println(“我是第一个”);
  5. try {
  6. Thread.sleep(500);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. System.out.println(“我虽然睡了一会,但我是第二个”);
  11. };
  12. };
  13. thread1.start();
  14. //在这阻塞主线程
  15. Thread thread2 = new Thread() {
  16. public void run() {
  17. try {
  18. thread1.join();
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }// 等待t1线程 执行完结,才继续向下执行 在这阻塞子线程
  22. System.out.println(“我是第三个”);
  23. };
  24. };
  25. thread2.start();
  26. }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,904
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,430
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,727