JAVA多线程二

Thread.Join()

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函数通过isAlive()判断当前线程是否结束,并且wait一定的时间。如果超出了这个时间,就会返回。

ThreadLocal

ThreadLocal指的是线程变量,它里面包含了一个存储结构,可以保存任意类型的变量。

public T get() { }
public void set(T value) { }
public void remove() { }
protected T initialValue() { }

上面是ThreadLocal调用的几个函数。

package com.thread;

import java.util.concurrent.TimeUnit;

public class Profile {
    private  static final ThreadLocal<Long> time_threadlocal
            = new ThreadLocal<Long>() {
        protected Long initialValue() {
            return System.currentTimeMillis();
        }
    };

    public static final void begin() {
        time_threadlocal.set(System.currentTimeMillis());
    }

    public static final long end() {
        return System.currentTimeMillis() - time_threadlocal.get();
    }

    public static void main(String args[]) throws InterruptedException {
        Profile.begin();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("cost " + Profile.end());
    }
}

上面的示例中,复写了initialValue函数,然后通过begin设置为当前的时间,通过end计算程序消耗的时间。这里不复写也可以,但是必须要在get函数之前调用set函数
参考:JAVA并发编程的艺术

原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5557964.html