찾다

 >  Q&A  >  본문

java - 对main线程使用join方法,为什么main线程处于一直阻塞状态?

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();
        }
    }
}

}

高洛峰高洛峰2888일 전430

모든 응답(1)나는 대답할 것이다

  • PHP中文网

    PHP中文网2017-04-17 18:00:52

    그럼 먼저 join 함수가 어떤 용도로 사용되는지 알아야 합니다! 먼저 문서를 살펴보겠습니다.

    으아악

    첫 번째 문장 Waits for this thread to die처럼 메인 스레드에서 "현재 스레드가 끝나기 전에 메인 스레드가 끝날 때까지 기다려야 합니다"를 실행하면 무한 루프가 아닌가요?

    회신하다
    0
  • 취소회신하다