线程01-Thread类,Runnable接口

Posted perferect

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程01-Thread类,Runnable接口相关的知识,希望对你有一定的参考价值。

常见面试题:创建一个线程的常用方法有哪些?Thread创建线程和Runnable创建线程有什么区别?
答案通常集中在,继承类和实现接口的差别上面;
如果深入问一些问题:1.要执行的任务写在run()方法中,为什么要用start()方法启动?等等问题
简单的问题还是可以回答一哈子,但是涉及到深入些的问题,就只能看看源码,才能更好的回答问题了:

1.为啥线程要用start()方法启动?

首先要从Thread类的源码入手:

  • Thread类实现了Runnable接口
public
class Thread implements Runnable {
  • 可以看出,Thread类里面有一个Runnable接口的元素,通过构造方法给Thread类里面的Runnable元素赋值;
   private Runnable target;
   public Thread(Runnable target) {
      init(null, target, "Thread-" + nextThreadNum(), 0);
  }
  private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
       //省略部分代码
        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
      //......省略部分代码
        this.target = target;//注意这里的赋值操作
        setPriority(priority);
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }
  • run方法很简单,就是判断是不是通过构造函数传入了Runnable接口,可以看出,线程的方法并没有执行;
 @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

  • start()方法中通过调用start0()执行Run()方法;类似于this.run();报错后也是忽略状态;
 public synchronized void start() {
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        group.add(this);

        boolean started = false;
        try {
            start0();
            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();

  • 可以借鉴的地方:
    将任务封装在单独的接口中,可以多种实现,通过统一的方法去调用;
interface A {
  run(){)
}
class B implements A {
 private A a;
 B(){}
 B(A a){this.a = a} 
 run(){
   if(a != null ){a.run} 
 }
 start(){this.run()}
}

2.Thread的几种状态

  • 类中给出的几种状态
public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * 具有指定等待时间的等待线程的线程状态。
         * 一个线程由于调用其中一个而处于定时等待状态
         * 以下有指定正轮候时间的方法:
         * sleep Thread.sleep
         * Object#wait(long) Object.wait} with timeout
         *  #join(long) Thread.join} with timeout
         *  LockSupport#parkNanos LockSupport.parkNanos
         *  LockSupport#parkUntil LockSupport.parkUntil
         */
        TIMED_WAITING,

        /**
         * 终止线程的线程状态。线程已经完成执行
         */
        TERMINATED;
    }





以上是关于线程01-Thread类,Runnable接口的主要内容,如果未能解决你的问题,请参考以下文章

java多线程

线程实现Runnable接口比继承Thread的优势

Java中的线程

多线程之实现Runnable接口及其优点

java中线程编程代码怎么写啊

Java多线程runnable