join方法及其调用yield sleep wait notify方法会对锁产生的影响

join方法

线程A执行了线程B的join方法,,线程A必须要等线程B执行完成后,线程A才能继续执行

感觉像是插队[捂脸]

package org.dance.day1;

import org.dance.tools.SleepTools;

/**
 * join方法的使用
 */
public class UseJoin {

    //
    static class JumpQueue implements Runnable {
        private Thread thread;//用来插队的线程

        public JumpQueue(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            try {
                System.out.println(thread.getName()+" will be join before "
                        +Thread.currentThread().getName());
                thread.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" terminted.");
        }
    }

    public static void main(String[] args) throws Exception {
        Thread previous = Thread.currentThread();//现在是主线程
        for (int i = 0; i < 10; i++) {
            //i=0,previous 是主线程,i=1;previous是i=0这个线程
            Thread thread =
                    new Thread(new JumpQueue(previous), String.valueOf(i));
            System.out.println(previous.getName()+" jump a queue the thread:"
                    +thread.getName());
            thread.start();
            previous = thread;
        }

        SleepTools.second(2);//让主线程休眠2秒
        System.out.println(Thread.currentThread().getName() + " terminate.");
    }
}

接下来说一下调用yield sleep wait notify方法会对锁产生的影响

yield:

  线程在执行yield以后,持有的锁是不会释放的

sleep:

  线程在进入Sleep之后,锁也是不会释放的

wait:

  调用wait方法之前,必须要先持有锁,调用wait方法以后,锁会被释放,当wait方法被唤醒时,线程会重新持有锁

notify:

  调用notify之前,也必须要持有锁,调用notify方法本身不会释放锁

作者:彼岸舞

时间:2020\09\16

内容关于:并发编程

本文来源于网络,只做技术分享,一概不负任何责任

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值