zoukankan      html  css  js  c++  java
  • 指定线程执行的顺序---join()

    线程T1,T2,T3分别启动,如何让其执行顺序变为T3>T2>T1:

    线程1:

     1 package test6;
     2 
     3 public class Thread1 extends Thread{
     4 
     5     private Thread thread2;
     6     public Thread1(Thread thread2){
     7         this.thread2=thread2;
     8     }
     9     @Override
    10     public void run(){
    11         try {
    12             thread2.join();
    13             System.out.println("线程1在执行");
    14         } catch (InterruptedException e) {
    15             e.printStackTrace();
    16         }
    17     }
    18 }

    线程2:

     1 package test6;
     2 
     3 public class Thread2 extends Thread{
     4 
     5     private Thread thread3;
     6     public Thread2(Thread thread3){
     7         this.thread3=thread3;
     8     }
     9     @Override
    10     public void run(){
    11         try {
    12             thread3.join();
    13             System.out.println("线程2在执行");
    14         } catch (InterruptedException e) {
    15             e.printStackTrace();
    16         }
    17     }
    18 }

    线程3:

     1 package test6;
     2 
     3 public class Thread3 extends Thread{
     4 
     5     @Override
     6     public void run(){
     7         try {
     8             System.out.println("线程3在执行。。。");
     9             Thread.sleep(2000);
    10         } catch (InterruptedException e) {
    11             // TODO Auto-generated catch block
    12             e.printStackTrace();
    13         }
    14     }
    15 }

    执行:

     1 package test6;
     2 
     3 public class Run {
     4 
     5     public static void main(String[] args) {
     6         Thread3 t3=new Thread3();
     7         Thread2 t2=new Thread2(t3);
     8         Thread1 t1=new Thread1(t2);
     9         t1.start();
    10         t2.start();
    11         t3.start();
    12     }
    13 }

    如图:启动顺序为t1,t2,t3.但是使用join后,执行顺序为t3,t2,t1

    join的作用:使当前线程等正在执行的线程执行完。join内部调用的是wait方法没,所以释放锁。sleep不释放锁。

  • 相关阅读:
    Documents
    gitlab 安装和配置
    git相关知识
    马俊龙ansible教程分享
    源码安装python 报错,openssl: error while loading shared libraries: libssl.so.1.1
    jumpserver 常见错误解决
    nginx 定义:响应头和请求头
    gcc入门(下)
    gcc入门(上)
    awk命令
  • 原文地址:https://www.cnblogs.com/noaman/p/6159306.html
Copyright © 2011-2022 走看看