zoukankan      html  css  js  c++  java
  • 多线程基础知识---join方法

    join方法的作用

    thread.join()方法用于把指定的线程加入到当前线程中,把当前线程的CPU执行时间让给另一个线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。

    threadA.join();      //把当前线程执行时间让给threadA线程,直到threadA执行完毕才会继续执行当前线程
    threadA.join(1000);  //把当前线程执行时间让给threadA线程,1000毫秒后,A、B两个线程再重新竞争

    join方法的源码如下,可以看出是通过while和wait的方式进行控制:

    /**
         *  Waits at most <code>millis</code> milliseconds for this thread to  
         * die. A timeout of <code>0</code> means to wait forever.    
         */
        //此处A timeout of 0 means to wait forever 字面意思是永远等待,其实是等到t结束后。
        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;
                }
            }
        }

    下面这个程序的输出结果是多少?A:0    B:1000    C:1   D:不确定

    public class ThreadTest extends Thread {
    
        public static int a = 0;
    
        public void run() {
            for (int k = 0; k < 100000; k++) {
                a = a + 1;
            }
        }
    
        public static void main(String[] args) throws Exception {
            Thread t = new ThreadTest();
            t.start();
            t.join(1);
            System.out.println(a);
        }
    }

     答案是:D。因为t.start()只是让线程进入了RUNNABLE状态,但并不一定在1毫秒内执行到t线程的run方法。如果没有走进t线程的run方法,直接执行了主线程的打印语句,则输出结果为0;如果进入了t线程的run方法,并且在1毫秒内将t线程的run方法执行完毕,则输出结果为100000;否则,可能是0~100000之间的任意数字。因此最终答案不能确定

  • 相关阅读:
    PLSQL学习笔记 wm_concat
    Oracle ERP 公司间往来的解决方案(转载)
    Excel单元格设成只读
    PLSQL笔记 存在性检查
    PL/SQL编程技巧
    查看Oracle EBS克隆Clone时间
    用wm_concat合并行及merge into更新
    商务英语900句
    外企公司常用英文缩写
    ASP.NET 2.0 XML 系列(5):用XmlReader读取XML文档
  • 原文地址:https://www.cnblogs.com/aligege/p/11536204.html
Copyright © 2011-2022 走看看