以Runnable实现类的对象时说的作为Thread的target是什么?

几乎一年没看java,问下下面代码中的“以Runnable实现类的对象 作为Thread的target来创建Thread对象”
什么叫做Thread的target

public class SecondCreateThread implements Runnable {
    public void run() {//线程执行体
        for( int i=0; i<20; ++i ){
            System.out.println( Thread.currentThread().getName()+" "+i );
        }
    }
    public static void main(String[] args) {
        for( int i=0; i<30; ++i ){
            System.out.println( Thread.currentThread().getName()+" "+i );
            
            if( i==20 ){            
                SecondCreateThread target = new SecondCreateThread(  );
                //以Runnable实现类的对象 作为Thread的target来创建Thread对象
                new Thread( target, "线程1" ).start();
                new Thread( target, "线程2" ).start();
                
            }
        }
        
    }
}
阅读 6.3k
3 个回答

准确的说是需要放到子线程去执行的代码
直接new SecondCreateThread 执行其run方法的时候还是在主线程执行。这个就是正常的方法调用而已。并没有开线程

一般遇到这种问题,第一想法去看看jdk 的api。

创建新执行线程有两种方法。一种方法是将类声明为 Thread 的子类。该子类应重写 Thread 类的 run 方法。接下来可以分配并启动该子类的实例。例如,计算大于某一规定值的质数的线程可以写成:

     class PrimeThread extends Thread {
         long minPrime;
         PrimeThread(long minPrime) {
             this.minPrime = minPrime;
         }
 
         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

然后,下列代码会创建并启动一个线程:

     PrimeThread p = new PrimeThread(143);
     p.start();

创建线程的另一种方法是声明实现 Runnable 接口的类。该类然后实现 run 方法。然后可以分配该类的实例,在创建 Thread 时作为一个参数来传递并启动。采用这种风格的同一个例子如下所示:

     class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }
 
         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

然后,下列代码会创建并启动一个线程:

     PrimeRun p = new PrimeRun(143);
     new Thread(p).start();

每个线程都有一个标识名,多个线程可以同名。如果线程创建时没有指定标识名,就会为其生成一个新名称。

二种方式,核心都是实现run方法,在run方法中实现自己的逻辑,第一个方式是通过继承来重写,实现自己的run方法,第二种方式是通过组合的方式来实现自己的run方法。题主使用的是第二种方式,SecondCreateThread 对象就是那个target,线程会去执行你的target中的run方法。

看看thread的源代码

/**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    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();
            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();

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

从上面的源代码中可以看到:
一旦调用start()方法,则会通过JVM找到run()方法去执行,怎么执行自己的逻辑代码呢?一种是继承Thread,然后重写run方法,jvm执行的就是自己的写的run方法了。一种是传入一个target,然后在Thread的run方法中调用target的run方法。

其实这个 target 只是说Runnable Thread.traget 这个字段而已:


public
class Thread implements Runnable {

    /* What will be run. */
    private Runnable target;
    
        /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    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();
            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();

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

}

也就是说,Thread.run 本身的逻辑就只是判断一下自身的 target 是否为空,非空就运行它。
你通过构造方法传进一个 Runnable 就是给 Thread.target 这个字段赋值。
通过覆写 Thread.run 方法就只是不用 Thread.target 来保存运行逻辑罢了。

因为 Thread.start0 这个本地方法并不关心你的 target 有没有,它只负责运行 Thread.run 这个方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题