我已经在Thread中编写了一个基本代码,得到的输出令人惊讶。
public class ThreadImp implements Runnable{
public static void main(String[] args) {
ThreadImp threadImp = new ThreadImp();
Thread t =new Thread(threadImp);
t.setName("Fred");
t.start();
threadImp.run();
t.run();
}
public void run(){
System.out.println("Current Thread: "+ Thread.currentThread());
}
}
我期望这里的输出是它将被打印
当前线程:线程[main,5,main]
当前线程:线程[Fred,5,main]
当前线程:线程[main,5,main]
我可以理解的结果是,我正在创建的线程只有一个,即线程Fred。其他两个对run方法的调用就像调用普通方法一样。
但是我不明白的是,有时当我执行相同的程序时,会得到以下输出。所以任何人都可以向我解释它为什么会这样。
当前线程:线程[main,5,main]
当前线程:线程[Fred,5,main]
您调用了Thread.run()
(通常不应直接调用),并且如果Thread
完成并清理了它,则不会执行任何操作:
@Override public void run() { if (target != null) { target.run(); } }
资料来源:Java 7更新79
target
提供的可运行位置在哪里。该字段target
设置为null
线程结束时的时间:
/** * This method is called by the system to give a Thread * a chance to clean up before it actually exits. */ private void exit() { if (group != null) { group.threadTerminated(this); group = null; } /* Aggressively null out all reference fields: see bug 4006245 */ target = null; /* Speed the release of some of these resources */ threadLocals = null; inheritableThreadLocals = null; inheritedAccessControlContext = null; blocker = null; uncaughtExceptionHandler = null; }
资料来源:Java 7更新79
因此,确切的输出(包括订单,如果您收到两条或三条消息)取决于计时,调度等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句