java version

jdk8_151 64 位

代码

package com.clark;

public class MyRunnable implements Runnable {

    public void run() {
        System.out.println("hh!");
    }
}

package com.test;

import com.clark.MyRunnable;

public class Run {

    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();

        Thread t1 = new Thread(thread);
        t1.start();
        System.out.println("Over!");
    }

}

问题很简单,上面的代码有哪些可能的输出?为什么?

自答

其实这个是自己看书,随便想出来玩的,在执行过程中呢,发现有两个答案,
输出一:

Over!
hh!

输出二:

Over!
hh!
hh!

开始呢,我以为是 BUG 来的,后来发现,当线程 thread 先执行的时候就是输出一,当 t1 先执行的时候就是输出二,
如何证明呢?只要将线程 ID 输出就可以了

public class MyRunnable implements Runnable {

    public void run() {
        System.out.println("currentId:"+ Thread.currentThread().getId());
        System.out.println("hh!");
    }
}

public class Run {

    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        System.out.println("thread-0:" + thread.getState());
        thread.start();
        System.out.println("thread-id:" + thread.getId());
        System.out.println("thread-1:" + thread.getState());

        Thread t1 = new Thread(thread);

        System.out.println("t1-id:" + t1.getId());
        System.out.println("t1-state:" + t1.getState());
        System.out.println("thread-2:" + thread.getState());
        System.out.println("t1-0:" + thread.getState());
        t1.start();
        System.out.println("t1-state:" + t1.getState());
        System.out.println("t1-1:" + thread.getState());
        System.out.println("Over!");
    }

}

但是一想,这也还是很奇怪,即使两个线程执行顺序不同,也应该是输出二才对,怎么会有输出一的情况呢?
还是有些疑惑的


↙↙↙阅读原文可查看相关链接,并与作者交流