java并发编程实战-35-join

package com.roocon.thread.tb2;

public class Demo {

	public void a(Thread joinThread) {
		System.out.println("方法a执行了...");
		joinThread.start();
		try {
			joinThread.join();//加塞join了
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("a方法执行完毕...");

	}

	public void b() {
		System.out.println("加塞线程开始执行....");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("加塞线程执行完毕...");
	}

	public static void main(String[] args) {
		Demo demo = new Demo();
		Thread joinThread = new Thread(new Runnable() {

			@Override
			public void run() {
				demo.b();
			}
		});

		new Thread(new Runnable() {

			@Override
			public void run() {
				demo.a(joinThread);
			}
		}).start();
	}

}

原理:

 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()) {//加塞线程joinThread活着
                wait(0);//wait锁的什么东西是synchronized当前锁的对象 wait是调用a方法的线程,是调用加塞线程的线程 哪个线程调用的就锁哪个线程 
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

如何定义alive呢?

 sleep也算是活着的。执行完destory会唤醒所有的等待线程。调用线程自身的notifyAll方法。

---------------------35-------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值