java - 对main线程使用join方法,为什么main线程处于一直阻塞状态?
高洛峰
高洛峰 2017-04-17 17:58:52
0
1
438

public class JoinTest {

public static void main(String[] args) throws InterruptedException {
    MyThread3 thread=new MyThread3();
    thread.start();
    //thread.join(1);//将主线程加入到子线程后面,不过如果子线程在1毫秒时间内没执行完,则主线程便不再等待它执行完,进入就绪状态,等待cpu调度
    System.out.println(Thread.currentThread());
    Thread.currentThread().join();
    for(int i=0;i<30;i++){
        System.out.println(Thread.currentThread().getName() + "线程第" + i + "次执行!");
    }
}

}

class MyThread3 extends Thread {

@Override
public void run() {
    
    for (int i = 0; i < 1000; i++) {
        try {
            System.out.println(this.getName() + "线程第" + i + "次执行!");
            Thread.sleep(1);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

membalas semua(1)
Ty80

Kemudian anda mesti tahu dulu fungsi join digunakan untuk apa! Mari lihat dokumentasi dahulu:

/**
 * Waits for this thread to die.
 *
 * <p> An invocation of this method behaves in exactly the same
 * way as the invocation
 *
 * <blockquote>
 * {@linkplain #join(long) join}{@code (0)}
 * </blockquote>
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */

Seperti yang dinyatakan dalam ayat pertama Waits for this thread to die, jika anda melaksanakan "Saya perlu menunggu sehingga utas utama tamat sebelum utas semasa tamat" pada utas utama, bukankah ini gelung tak terhingga?

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan