zoukankan      html  css  js  c++  java
  • Thread的方法join()使用

    join()的作用:Waits for this thread to die.等待线程对象销毁。
    在Thread源码中可以看到join源码是使用了wait()方法来实现等待功能。

    因为join()内部使用了wait()方法实现,wait方法被调用后线程会释放锁,因此join方法也具有释放锁的特点。

    这也是join()、wait()和sleep()的区别,sleep是不会释放锁的。

    JDK1.8中join源码如下:

    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);
                }
            } else {
                while (isAlive()) {
                    long delay = millis - now;
                    if (delay <= 0) {
                        break;
                    }
                    wait(delay);
                    now = System.currentTimeMillis() - base;
                }
            }
        }
    

     下面的测试代码能说明join能够使线程排队运行。

    /**
     * @author monkjavaer
     * @date 2018/12/15 16:36
     */
    public class JoinThread implements Runnable{
        @Override
        public void run() {
            System.out.println("I am JoinThread run ...");
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

     join()测试:

    public class JoinTest {
        public static void main(String[] args) {
            try {
                Thread thread = new Thread(new JoinThread());
                thread.start();
                thread.join();
                System.out.println("....after JoinThread.....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

      输出:

    I am JoinThread run ...
    ....after JoinThread.....

     

  • 相关阅读:
    原型链与析构函数
    django篇-路由系统介绍
    mvc与mtv
    模板初探
    安装和创建django项目
    一分钟学会定时删除日志的 Shell 脚本
    svn其中一种备份方式svnsync
    mysql企业实战(二)之主从复制,读写分离,双主,以及高可用
    mysql企业实战(一)
    nginx详解
  • 原文地址:https://www.cnblogs.com/monkjavaer/p/10123853.html
Copyright © 2011-2022 走看看