zoukankan      html  css  js  c++  java
  • Java多线程中的join方法

    新建一个Thread,代码如下:

     1 package com.thread.test;
     2 
     3 public class MyThread extends Thread {
     4     private String name;
     5     public MyThread(String name) {
     6         this.name = name;
     7     }
     8     @Override
     9     public void run() {
    10         for (int i = 0; i < 100; i++) {
    11             System.out.println(name+"["+i+"]");
    12         }
    13         super.run();
    14     }
    15 }

    之后新建测试类,代码如下:

     1 package com.thread.test;
     2 /*
     3  * 0-50执行的是主线程,50-100执行的是A线程,并且将A线程完全执行完后才继续执行主线程
     4  */
     5 public class ThreadDemo{
     6     public static void main(String[] args) {
     7         MyThread t = new MyThread("A");
     8         t.start();
     9         for (int i = 0; i < 100; i++) {
    10             if (i>50) {
    11                 try {
    12                     t.join();
    13                 } catch (InterruptedException e) {
    14                     e.printStackTrace();
    15                 }
    16             }
    17             System.out.println("主线程"+"["+i+"]");
    18         }
    19     }
    20 }

    下面是Java Platform SE8 API中对Thread中Join方法的解释:

    public final void join(long millis)
                    throws InterruptedExceptionWaits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. 
    This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
    
    Parameters: 
    millis - the time to wait in milliseconds 
    Throws: 
    IllegalArgumentException - if the value of millis is negative 
    InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
  • 相关阅读:
    多线程调用本质
    音频编码解码器库 libZPlay
    C#多线程代码调试技巧
    SharpMap实践代码
    Work Queue based multithreading
    (转)C#写的NoSQL开源系统(系列)
    A .NET State Machine Toolkit Part I
    在线开发环境地址
    数字音乐商KKBOX三季度将进军日本市场
    苹果官方购置iPad用户将获1100元退款
  • 原文地址:https://www.cnblogs.com/kuangwong/p/6274249.html
Copyright © 2011-2022 走看看