1. 程式人生 > 實用技巧 >join方法及其呼叫yield sleep wait notify方法會對鎖產生的影響

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."); } }

接下來說一下呼叫yieldsleepwaitnotify方法會對鎖產生的影響

yield:

  執行緒在執行yield以後,持有的鎖是不會釋放的

sleep:

  執行緒在進入Sleep之後,鎖也是不會釋放的

wait:

  呼叫wait方法之前,必須要先持有鎖,呼叫wait方法以後,鎖會被釋放,當wait方法被喚醒時,執行緒會重新持有鎖

notify:

  呼叫notify之前,也必須要持有鎖,呼叫notify方法本身不會釋放鎖

作者:彼岸舞

時間:2020\09\16

內容關於:併發程式設計

本文來源於網路,只做技術分享,一概不負任何責任