java多線程源碼解讀 start轧抗,run,join瞬测,yied

java
/**

  • Created by 陳奇 on 2017/4/14 0014.
    */
    public class ThreadHelloWord implements Runnable {
    @Override
    public void run() {
    System.out.println("hello word");
    }

    public static void main(String[] args) {
    ThreadHelloWord t = new ThreadHelloWord();
    Thread th = new Thread(t);
    System.out.println("states="+th.getState());
    th.start();
    System.out.println(th.getName());
    System.out.println("states="+th.getState());

    }
    }

* 這一段代碼創(chuàng)建了一個(gè)線程横媚,并打印出hello Word,
先看一下runnable接口源碼吧.
```java```
/* @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
} ```
*  Runnable自jdk1.0定義月趟,只定義了一個(gè)run方法灯蝴。實(shí)現(xiàn)接口必須實(shí)現(xiàn)其方法,所以重寫了run方法孝宗。
在看下Thread類
```java```
public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }
  • Thread類實(shí)現(xiàn)了runnable接口穷躁,并獲取寄存器,也就是說每一個(gè)線程都有一個(gè)寄存器因妇,再看下star()方法
    java
    public synchronized void start() {
    /**
    * This method is not invoked for the main method thread or "system"
    * group threads created/set up by the VM. Any new functionality added
    * to this method in the future may have to also be added to the VM.
    *
    * A zero status value corresponds to state "NEW".
    */
    if (threadStatus != 0)
    throw new IllegalThreadStateException();

      /* Notify the group that this thread is about to be started
       * so that it can be added to the group's list of threads
       * and the group's unstarted count can be decremented. */
      group.add(this);
    
      boolean started = false;
      try {
          start0();    //調(diào)用本地方法
          started = true;
      } finally {
          try {
              if (!started) {
                  group.threadStartFailed(this);
              }
          } catch (Throwable ignore) {
              /* do nothing. If start0 threw a Throwable then
                it will be passed up the call stack */
          }
      }
    

    }
    private native void start0(); //本地方法執(zhí)行線程

這里有一個(gè)小疑問问潭,既然線程有自己獨(dú)立的寄存器為什么還要加鎖呢猿诸?

yield()方法讓出執(zhí)行權(quán)
 ```java```
  public static native void yield(); //本地方法
package com.cn.threadpool;

/**
 * Created by 陳奇 on 2017/4/14 0014.
 */
public class ThreadHelloWord extends Thread {
    private String helloword;
    ThreadHelloWord(){}
    ThreadHelloWord(String helloword){
       super(helloword);
    }
    @Override
    public void run() {
        for (int i = 0; i <20 ; i++) {
            System.out.println("" + this.getName() + "-----" + i);
            // 當(dāng)i為10時(shí),該線程就會(huì)把CPU時(shí)間讓掉睦授,讓其他或者自己的線程執(zhí)行(也就是誰(shuí)先搶到誰(shuí)執(zhí)行)
            if (i == 10) {
                this.yield();
            }
        }
    }

    public static void main(String[] args) {
        ThreadHelloWord h = new ThreadHelloWord("h");
        ThreadHelloWord w = new ThreadHelloWord("w");
        Thread th = new Thread(h);
        Thread tw = new Thread(w);
        th.start();
        tw.start();

    }
}
Paste_Image.png
Paste_Image.png

join() 方法
源碼
java
public final void join() throws InterruptedException {
join(0);
}
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);          // 調(diào)用wait方法
            now = System.currentTimeMillis() - base;
        }
    }
}
join方法調(diào)用的是object的wait方法两芳,
demo
  ```java```
/**
 * Created by 陳奇 on 2017/4/16 0016.
 */
public class JoinTest extends Thread {
    JoinTest(String name){
        super(name);
    }
    @Override
    public void run() {
        try {
            sleep(30);
            System.out.println(this.getName()+"____run ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new JoinTest("t"));
        Thread t1 = new Thread(new JoinTest("t1"));
        t.start();                                          // wait(0)摔寨,立即執(zhí)行
        t.join();
        t1.start();

        t1.join(10); //main線程等待時(shí)間
        System.out.println("main end");
    }
}
Paste_Image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末去枷,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子是复,更是在濱河造成了極大的恐慌删顶,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件淑廊,死亡現(xiàn)場(chǎng)離奇詭異逗余,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)季惩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門录粱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人画拾,你說我怎么就攤上這事啥繁。” “怎么了青抛?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵旗闽,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我蜜另,道長(zhǎng)适室,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任举瑰,我火速辦了婚禮捣辆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘此迅。我一直安慰自己汽畴,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布邮屁。 她就那樣靜靜地躺著整袁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪佑吝。 梳的紋絲不亂的頭發(fā)上坐昙,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天,我揣著相機(jī)與錄音芋忿,去河邊找鬼炸客。 笑死疾棵,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的痹仙。 我是一名探鬼主播是尔,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼开仰!你這毒婦竟也來了拟枚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤众弓,失蹤者是張志新(化名)和其女友劉穎恩溅,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體谓娃,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡脚乡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了滨达。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片奶稠。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖捡遍,靈堂內(nèi)的尸體忽然破棺而出锌订,到底是詐尸還是另有隱情,我是刑警寧澤稽莉,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布瀑志,位于F島的核電站,受9級(jí)特大地震影響污秆,放射性物質(zhì)發(fā)生泄漏劈猪。R本人自食惡果不足惜爷辱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一辣之、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧悍募,春花似錦庸推、人聲如沸常侦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)聋亡。三九已至,卻和暖如春际乘,著一層夾襖步出監(jiān)牢的瞬間坡倔,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留罪塔,地道東北人投蝉。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像征堪,于是被迫代替她去往敵國(guó)和親瘩缆。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

推薦閱讀更多精彩內(nèi)容