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

    package com.qjc.thread;
    
    public class JoinExcemple {
        // join方法就是用来同步的
        public static void main(String[] args) throws InterruptedException {
            ThreadJoinTest threadJoinA = new ThreadJoinTest("线程A");
            ThreadJoinTest threadJoinB = new ThreadJoinTest("线程B");
    
            Thread threadA = new Thread(threadJoinA);
            Thread threadB = new Thread(threadJoinB);
            threadA.start();
            threadA.join();// 在main线程中,调用threadA线程的join方法,主线程就会放弃cpu,等待threadA执行完毕后再执行
            threadB.start();
        }
    }
    
    class ThreadJoinTest implements Runnable {
        String threadName;
    
        public ThreadJoinTest(String threadName) {
            this.threadName = threadName;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                System.out.println(this.threadName + "----" + i);
            }
        }
    
    }

     大家可以看一下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);//如果活着则等待,参数为0,说明必须等待调用join()方法的线程执行完毕后再执行
                }
            } else {
                while (isAlive()) {
                    long delay = millis - now;
                    if (delay <= 0) {
                        break;
                    }
                    wait(delay);
                    now = System.currentTimeMillis() - base;
                }
            }
        }
    /**
     * Tests if this thread is alive. A thread is alive if it has
     * been started and has not yet died.
     *
     * @return  <code>true</code> if this thread is alive;
     *          <code>false</code> otherwise.
     * 如果该线程已经启动,但是还没有结束,则就是活着的
     */
    public final native boolean isAlive();
    
    /**
     * Causes the current thread to wait until either another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object, or a
     * specified amount of time has elapsed.
     * 该线程会一直等待,直到被唤醒
     */
    public final native void wait(long timeout) throws InterruptedException;

    所以,从源码可以看出,主线程中调用了ThreadA的join()方法,则相当于调用了ThreadA的wait()方法,

    当ThreadA线程执行完后会调用自身的notifyAll()方法唤醒主线程,从而达到了同步的目的

  • 相关阅读:
    inotifywait 目录或文件的监控
    outlook邮件中样式问题
    IE8兼容问题
    12px以下字体显示问题
    box-shadow
    cropper.js图片裁剪
    利用vcard和qrcode.js生成二维码导入联系人
    使用link rel="shortcut icon"为网页标题加图标
    将input或textarea设置为disabled的样式问题
    img没有src属性时自动出现边框
  • 原文地址:https://www.cnblogs.com/java-spring/p/8872796.html
Copyright © 2011-2022 走看看