JAVA多线程之(join)

来源:互联网 发布:手游源码出售 编辑:程序博客网 时间:2024/05/17 08:35

 java多线程中,join方法是主线程等待一个子线程结束后再继续执行主线程后续代码,wait方法会让线程进入阻塞状态,并且会释放线程占有的锁,并交出CPU执行权限,由于wait方法会让线程释放对象锁,研究java Thread类的join方法发现,其实join方法也是调用wait方法实现,所以join方法同样会让线程释放对一个对象持有的锁。

Thread类的join方法的源代码:

     

 /**     * Waits at most <code>millis</code> milliseconds for this thread to      * die. A timeout of <code>0</code> means to wait forever.      *     * @param      millis   the time to wait in milliseconds.     * @exception  InterruptedException if any thread has interrupted     *             the current thread.  The <i>interrupted status</i> of the     *             current thread is cleared when this exception is thrown.     */    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;    }}    }
Thread join 方法实例代码如下:

package nc.com.thread.traditional.example;/*** @ClassName: ThreadJoin * @Description: TODO(这里用一句话描述这个类的作用) * @author A18ccms a18ccms_gmail_com * @date 2015-12-19 下午06:35:15 * */public class ThreadJoin { private Object object = new Object(); private int i = 10;public static void main(String[] args) {/** * 有join时输出: */ThreadJoin j = new ThreadJoin();DemoThread t1 = j.new DemoThread();t1.start();try {//执行join方法后,主线程进入阻塞状态,直到子线程执行结束t1.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("----------主线程已经等到了子线程执行结束,继续执行主线程--------");} class DemoThread extends Thread{    @Override    public void run() {        synchronized (object) {            i++;            System.out.println("i:"+i);            try {                System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态");            } catch (Exception e) {                // TODO: handle exception            }            System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束");            i++;            System.out.println("i:"+i);        }    }}}

输出:

   i:11
线程Thread-0进入睡眠状态
线程Thread-0睡眠结束
i:12
----------主线程已经等到了子线程执行结束,继续执行主线程--------

0 0
原创粉丝点击