线程的启动 - 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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章