今天研究了一下,join()方法在API中的解释是“等待线程终止”,那等待的线程当然是main thread。 在main thread 中创建的 t 和 t2 thread,都是独立的,所以当t join 到main thread 中,t2 依然执行自己的,并不会停止。

解决方案 »

  1.   

    所谓串行,也只是串行了main thread 和 t thread,使main thread 等待 t thread 执行结束。
      

  2.   

    join就是调用方法差不多,等方法结束了,继续运行线程
      

  3.   


    那这个例子中,t2 thread 应该不会被t thread 影响的哦
      

  4.   

    是当前线程调用join方法会等那线程运行完 再运行自己的线程。这里是main调用join吧? 不是t2调用join~所以是不会受影响的
      

  5.   

    0 t2
    1 t2
    0 t
    2 t2
    3 t2
    4 t2
    5 t2
    6 t2
    7 t2
    8 t2
    9 t2
    1 t
    2 t
    3 t
    4 t
    5 t
    6 t
    7 t
    8 t
    9 t
    main thread: 0
    main thread: 1
    main thread: 2
    main thread: 3
    main thread: 4这是循环10次我跑的结果,循环1000次就乱套了,3个线程在竞争资源
    我凌乱了,不知道要得出了神马结论。
      

  6.   


    没有3个线程在竞争呀,main thread 是等待t thread 结束之后运行的,这没错。t thread 和 t2 thread 它们是相互独立运行,但是打印的时间有快有慢,所以看到的结果好像是t 和 t2 thread 在相互竞争。
      

  7.   

    我是将,将循环次数改到1000甚至更大,就会看到3个线程竞争,包括main thread,可能更环境有关系吧,lz可以在不同环境上也试试。
      

  8.   

    你的结果会使main thread 在t thread 之前运行吗?
      

  9.   

    我这边不会呀,你是哪个thread 先 start的?你那边是什么环境呀,我这是ubuntu
      

  10.   

    14楼,我试过了,这个真会。一旦t.join()运行了,主线程相当于运行了t.wait(), 这个是要等线程t运行结束主线程才能醒来呢,怎么会有主线程会在t结束之前运行呢?
    Thread原码里,是这样定义的 :    public final void join() throws InterruptedException {
            join(0);
        }
    。。
        public final synchronized void join(long millis)
        throws InterruptedException {
            long base = System.currentTimeMillis();
            long now = 0;        if (millis < 0) {
                throw new IllegalArgumentException("timeout value is negative");
            }        if (millis == 0) {
                while (isAlive()) {
                    wait(0);//这里运行的wait
                }
            } else {