線程的啓動 - run 和 start 的區別

package com.ssm.jk.studyNotes.thread;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;

public class T {

    public class T1 implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			String threadName = Thread.currentThread().getName();
			System.out.println("T1".concat(threadName));
		}
    }
    
    public static void main(String[] args) {
		T1 t1 = new T().new T1();
		t1.run();
		t1.run();
		t1.run();
		new Thread(t1).start();
		new Thread(t1).start();
		new Thread(t1).start();
		Thread t3 = new Thread(t1);
		t3.stop();
		t3.start();
		t1.run();
	}

//執行結果1
T1main
T1main
T1main
T1Thread-0
T1Thread-1
T1Thread-2
T1main
T1Thread-3
//執行結果2
T1main
T1main
T1main
T1Thread-0
T1main
T1Thread-1
T1Thread-2
T1Thread-3

   run 和  start 的區別
   以上代碼我們執行幾次,會發現:
    結果是始終有三個run執行後,纔會有後面的亂序(一次run和四次start的執行順序是不確定的)
  run     單線程,用的是main的線程  ,是按順序執行的。相當於mian執行4次T1的run方法
  start   多線程,用的是每次創建的線程   (我們通過打印的當前線程的名稱可以看出),每個線程之間會有競爭關係,每次執行順序不一樣  。相當於4個線程執行T1的run方法

 

以下是1.6 和1.8兩個版本的源碼,不管start實現邏輯如何變化,thread始終是runable的實現類。

1.6
public interface Runnable
    {

        public abstract void run();
    }
    
    public synchronized void start()
    {
        if(threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if(stopBeforeStart)//如果在開始前停止,就停止
            stop0(throwableFromStop);
    }
    private native void start0();

 

1.8
public interface Runnable
    {

        public abstract void run();
    }
    
    public synchronized void start() {
        if (threadStatus != 0)//狀態校驗  0:NEW 新建狀態
            throw new IllegalThreadStateException();

        group.add(this);//添加進線程組

        boolean started = false;
        try {
            start0();//調用native方法執行線程run方法
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);//啓動失敗,從線程組中移除當前前程。
                }
            } catch (Throwable ignore) {
              
            }
        }
    }
    private native void start0();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章