浅析 Java Thread.join()

转载自:http://blog.csdn.net/bzwm/archive/2009/02/12/3881392.aspx

 

一、在研究join的用法之前,先明确两件事情。

1.join方法定义在Thread类中,则调用者必须是一个线程,

例如:

Thread t = new CustomThread();//这里一般是自定义的线程类

t.start();//线程起动

t.join();//此处会抛出InterruptedException异常

 

2.上面的两行代码也是在一个线程里面执行的。

 

以上出现了两个线程,一个是我们自定义的线程类,我们实现了run方法,做一些我们需要的工作;另外一个线程,生成我们自定义线程类的对象,然后执行

customThread.start();

customThread.join();

在这种情况下,两个线程的关系是一个线程由另外一个线程生成并起动,所以我们暂且认为第一个线程叫做“子线程”,另外一个线程叫做“主线程”。

 

二、为什么要用join()方法

主线程生成并起动了子线程,而子线程里要进行大量的耗时的运算(这里可以借鉴下线程的作用),当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join();方法了。

 

 

三、join方法的作用

在网上看到有人说“将两个线程合并”。这样解释我觉得理解起来还更麻烦。不如就借鉴下API里的说法:

“等待该线程终止。”

解释一下,是主线程(我在“一”里已经命名过了)等待子线程的终止。也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。(Waits for this thread to die.)

 

 

四、用实例来理解

写一个简单的例子来看一下join()的用法,一共三个类:

1.CustomThread 类

2. CustomThread1类

3. JoinTestDemo 类,main方法所在的类。

 

代码1:

view plaincopy to clipboardprint?
package wxhx.csdn2;  
/** 
 *  
 * @author bzwm 
 * 
 */ 
class CustomThread1 extends Thread {  
    public CustomThread1() {  
        super("[CustomThread1] Thread");  
    };  
    public void run() {  
        String threadName = Thread.currentThread().getName();  
        System.out.println(threadName + " start.");  
        try {  
            for (int i = 0; i < 5; i++) {  
                System.out.println(threadName + " loop at " + i);  
                Thread.sleep(1000);  
            }  
            System.out.println(threadName + " end.");  
        } catch (Exception e) {  
            System.out.println("Exception from " + threadName + ".run");  
        }  
    }  
}  
class CustomThread extends Thread {  
    CustomThread1 t1;  
    public CustomThread(CustomThread1 t1) {  
        super("[CustomThread] Thread");  
        this.t1 = t1;  
    }  
    public void run() {  
        String threadName = Thread.currentThread().getName();  
        System.out.println(threadName + " start.");  
        try {  
            t1.join();  
            System.out.println(threadName + " end.");  
        } catch (Exception e) {  
            System.out.println("Exception from " + threadName + ".run");  
        }  
    }  
}  
public class JoinTestDemo {  
    public static void main(String[] args) {  
        String threadName = Thread.currentThread().getName();  
        System.out.println(threadName + " start.");  
        CustomThread1 t1 = new CustomThread1();  
        CustomThread t = new CustomThread(t1);  
        try {  
            t1.start();  
            Thread.sleep(2000);  
            t.start();  
            t.join();//在代碼2里,將此處注釋掉  
        } catch (Exception e) {  
            System.out.println("Exception from main");  
        }  
        System.out.println(threadName + " end!");  
    }  

package wxhx.csdn2;
/**
 *
 * @author bzwm
 *
 */
class CustomThread1 extends Thread {
 public CustomThread1() {
  super("[CustomThread1] Thread");
 };
 public void run() {
  String threadName = Thread.currentThread().getName();
  System.out.println(threadName + " start.");
  try {
   for (int i = 0; i < 5; i++) {
    System.out.println(threadName + " loop at " + i);
    Thread.sleep(1000);
   }
   System.out.println(threadName + " end.");
  } catch (Exception e) {
   System.out.println("Exception from " + threadName + ".run");
  }
 }
}
class CustomThread extends Thread {
 CustomThread1 t1;
 public CustomThread(CustomThread1 t1) {
  super("[CustomThread] Thread");
  this.t1 = t1;
 }
 public void run() {
  String threadName = Thread.currentThread().getName();
  System.out.println(threadName + " start.");
  try {
   t1.join();
   System.out.println(threadName + " end.");
  } catch (Exception e) {
   System.out.println("Exception from " + threadName + ".run");
  }
 }
}
public class JoinTestDemo {
 public static void main(String[] args) {
  String threadName = Thread.currentThread().getName();
  System.out.println(threadName + " start.");
  CustomThread1 t1 = new CustomThread1();
  CustomThread t = new CustomThread(t1);
  try {
   t1.start();
   Thread.sleep(2000);
   t.start();
   t.join();//在代碼2里,將此處注釋掉
  } catch (Exception e) {
   System.out.println("Exception from main");
  }
  System.out.println(threadName + " end!");
 }
}

 

打印结果:

 

main start.//main方法所在的线程起动,但没有马上结束,因为调用t.join();,所以要等到t结束了,此线程才能向下执行。

[CustomThread1] Thread start.//线程CustomThread1起动

[CustomThread1] Thread loop at 0//线程CustomThread1执行

[CustomThread1] Thread loop at 1//线程CustomThread1执行

[CustomThread] Thread start.//线程CustomThread起动,但没有马上结束,因为调用t1.join();,所以要等到t1结束了,此线程才能向下执行。

[CustomThread1] Thread loop at 2//线程CustomThread1继续执行

[CustomThread1] Thread loop at 3//线程CustomThread1继续执行

[CustomThread1] Thread loop at 4//线程CustomThread1继续执行

[CustomThread1] Thread end. //线程CustomThread1结束了

[CustomThread] Thread end.// 线程CustomThread在t1.join();阻塞处起动,向下继续执行的结果

main end!//线程CustomThread结束,此线程在t.join();阻塞处起动,向下继续执行的结果。

 

修改一下代码,得到代码2:(这里只写出修改的部分)

view plaincopy to clipboardprint?
public class JoinTestDemo {  
    public static void main(String[] args) {  
        String threadName = Thread.currentThread().getName();  
        System.out.println(threadName + " start.");  
        CustomThread1 t1 = new CustomThread1();  
        CustomThread t = new CustomThread(t1);  
        try {  
            t1.start();  
            Thread.sleep(2000);  
            t.start();  
//          t.join();//在代碼2里,將此處注釋掉  
        } catch (Exception e) {  
            System.out.println("Exception from main");  
        }  
        System.out.println(threadName + " end!");  
    }  

public class JoinTestDemo {
 public static void main(String[] args) {
  String threadName = Thread.currentThread().getName();
  System.out.println(threadName + " start.");
  CustomThread1 t1 = new CustomThread1();
  CustomThread t = new CustomThread(t1);
  try {
   t1.start();
   Thread.sleep(2000);
   t.start();
//   t.join();//在代碼2里,將此處注釋掉
  } catch (Exception e) {
   System.out.println("Exception from main");
  }
  System.out.println(threadName + " end!");
 }
}

 

打印结果:

 

main start. // main方法所在的线程起动,但没有马上结束,这里并不是因为join方法,而是因为Thread.sleep(2000);

[CustomThread1] Thread start. //线程CustomThread1起动

[CustomThread1] Thread loop at 0//线程CustomThread1执行

[CustomThread1] Thread loop at 1//线程CustomThread1执行

main end!// Thread.sleep(2000);结束,虽然在线程CustomThread执行了t1.join();,但这并不会影响到其他线程(这里main方法所在的线程)。

[CustomThread] Thread start. //线程CustomThread起动,但没有马上结束,因为调用t1.join();,所以要等到t1结束了,此线程才能向下执行。

[CustomThread1] Thread loop at 2//线程CustomThread1继续执行

[CustomThread1] Thread loop at 3//线程CustomThread1继续执行

[CustomThread1] Thread loop at 4//线程CustomThread1继续执行

[CustomThread1] Thread end. //线程CustomThread1结束了

[CustomThread] Thread end. // 线程CustomThread在t1.join();阻塞处起动,向下继续执行的结果

 

 

五、从源码看join()方法

 

在CustomThread的run方法里,执行了t1.join();,进入看一下它的JDK源码:

view plaincopy to clipboardprint?
public final void join() throws InterruptedException {  
n(0);  

    public final void join() throws InterruptedException {
 join(0);
    }
 

然后进入join(0)方法:

 

view plaincopy to clipboardprint?
   /** 
    * Waits at most <code>millis</code> milliseconds for this thread to  
    * die. A timeout of <code>0</code> means to wait forever. //注意这句 
    * 
    * @param      millis   the time to wait in milliseconds. 
    * @exception  InterruptedException if another thread has interrupted 
    *             the current thread.  The <i>interrupted status</i> of the 
    *             current thread is cleared when this exception is thrown. 
    */ 
   public final synchronized void join(long millis) //参数millis为0.  
   throws InterruptedException {  
long base = System.currentTimeMillis();  
long now = 0;  
if (millis < 0) {  
           throw new IllegalArgumentException("timeout value is negative");  
}  
if (millis == 0) {//进入这个分支  
    while (isAlive()) {//判断本线程是否为活动的。这里的本线程就是t1.  
    wait(0);//阻塞  
    }  
} else {  
    while (isAlive()) {  
    long delay = millis - now;  
    if (delay <= 0) {  
        break;  
    }  
    wait(delay);  
    now = System.currentTimeMillis() - base;  
    }  
}  
   } 
    /**
     * Waits at most <code>millis</code> milliseconds for this thread to
     * die. A timeout of <code>0</code> means to wait forever. //注意这句
     *
     * @param      millis   the time to wait in milliseconds.
     * @exception  InterruptedException if another thread has interrupted
     *             the current thread.  The <i>interrupted status</i> of the
     *             current thread is cleared when this exception is thrown.
     */
    public final synchronized void join(long millis) //参数millis为0.
    throws InterruptedException {
 long base = System.currentTimeMillis();
 long now = 0;
 if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
 }
 if (millis == 0) {//进入这个分支
     while (isAlive()) {//判断本线程是否为活动的。这里的本线程就是t1.
  wait(0);//阻塞
     }
 } else {
     while (isAlive()) {
  long delay = millis - now;
  if (delay <= 0) {
      break;
  }
  wait(delay);
  now = System.currentTimeMillis() - base;
     }
 }
    }
 

 

 

 

单纯从代码上看,如果线程被生成了,但还未被起动,调用它的join()方法是没有作用的。将直接继续向下执行,这里就不写代码验证了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自动控制节水灌溉技术的高低代表着农业现代化的发展状况,灌溉系统自动化水平较低是制约我国高效农业发展的主要原因。本文就此问题研究了单片机控制的滴灌节水灌溉系统,该系统可对不同土壤的湿度进行监控,并按照作物对土壤湿度的要求进行适时、适量灌水,其核心是单片机和PC机构成的控制部分,主要对土壤湿度与灌水量之间的关系、灌溉控制技术及设备系统的硬件、软件编程各个部分进行了深入的研究。 单片机控制部分采用上下位机的形式。下位机硬件部分选用AT89C51单片机为核心,主要由土壤湿度传感器,信号处理电路,显示电路,输出控制电路,故障报警电路等组成,软件选用汇编语言编程。上位机选用586型以上PC机,通过MAX232芯片实现同下位机的电平转换功能,上下位机之间通过串行通信方式进行数据的双向传输,软件选用VB高级编程语言以建立友好的人机界面。系统主要具有以下功能:可在PC机提供的人机对话界面上设置作物要求的土壤湿度相关参数;单片机可将土壤湿度传感器检测到的土壤湿度模拟量转换成数字量,显示于LED显示器上,同时单片机可采用串行通信方式将此湿度值传输到PC机上;PC机通过其内设程序计算出所需的灌水量和灌水时间,且显示于界面上,并将有关的灌水信息反馈给单片机,若需灌水,则单片机系统启动鸣音报警,发出灌水信号,并经放大驱动设备,开启电磁阀进行倒计时定时灌水,若不需灌水,即PC机上显示的灌水量和灌水时间均为0,系统不进行灌水。
回答: java.lang.ClassNotFoundException是一个常见的错误,通常有几个可能的原因。首先,可能是项目中没有引入该类所属的jar包的坐标。你可以查看项目的pom文件,确认是否引入了该jar包的坐标,或者检查项目的Maven dependencies下是否有该class的jar包。\[1\]其次,可能是项目中多个maven坐标引入的jar包所依赖有所重叠,导致版本不一致产生冲突。你可以检查刚刚加入的maven坐标所依赖的jar包,与项目中其他maven坐标引入的jar包所依赖的jar包是否相同。\[1\]简单的解决办法是,将刚刚引入的jar包注释掉,然后复制Maven dependencies下所有的jar包名称到记事本文件中,再将刚刚引入的jar包解注释,再次复制所有的jar包名称到记事本文件中,最后使用代码比对工具比对两者所引入的jar包的区别,以查看是否有jar包依赖的冲突。\[1\]另外,有时候该错误可能是因为在部署路径下的lib文件夹中缺少相应的jar包。你可以进入到tomcat的部署路径下的lib文件夹,检查是否缺少相应的jar包。\[2\]最后,需要注意的是,该错误通常是在程序运行时找不到类,而不是在编译时找不到类。因此,即使在IDEA编译时没有报错,但在运行时仍然可能找不到对应的类。\[3\]希望这些解释能帮助你解决java.lang.ClassNotFoundException的问题。 #### 引用[.reference_title] - *1* [maven工程下 java.lang.ClassNotFoundException原因浅析](https://blog.csdn.net/farYang/article/details/53168233)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Maven项目下java.lang.ClassNotFoundException的解决方法](https://blog.csdn.net/zym2895756/article/details/78233688)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [maven依赖传统导致的 java.lang.NoClassDefFoundError和ClassNotFoundException产生原因以及解决方法](https://blog.csdn.net/qq_45171957/article/details/126899231)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值