码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程中的join方法

时间:2017-01-12 02:45:23      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:java   dex   com   cat   span   demo   thrown   row   isa   

新建一个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.

 

Java多线程中的join方法

标签:java   dex   com   cat   span   demo   thrown   row   isa   

原文地址:http://www.cnblogs.com/kuangwong/p/6274249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!