首页
学习
活动
专区
工具
TVP
发布

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

内容关于:并发编程

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

下一篇
举报
领券