2016-06-14 64 views
1
class SimpleThreading 
{ 
    public static void main(String... args) 
    { 
     Thread t=new Thread(); 
     System.out.println(t.getName()); 
     System.out.println(Thread.currentThread().getName()); 
     t.start(); 
     System.out.println(Thread.currentThread().getName()); 
    } 
} 

书面声明t.start()后,它应该打印当前线程的“线程0”,这是默认的JVM.But给它的名字将再次打印主。任何人都可以清除我的疑惑,我哪里出错了?的上面的代码输出为: 线程0 主 主主线程和当前Thread

+0

't.start()'将启动一个新的* *线程。它不会影响运行'main()'方法的线程,即“Main”线程。 – Andreas

回答

2

你的主要方法在Main线程中运行。因此,双方的println声明前t.start()打印Main

您的第二个线程什么都不做,因为您没有将任何Runnable实例传递给Thread构造函数。

如果传递一个Runnable实例的Thread构造,并且Runnablerun()方法包括System.out.println(Thread.currentThread().getName());,你会看到Thread-0打印。

例如,如果正在使用的Java 8,可以更换

Thread t=new Thread(); 

Thread t=new Thread(()->{System.out.println(Thread.currentThread().getName());}); 

也可以在写入相同的逻辑预爪哇8代码:

Thread t=new Thread(new Runnable() { 
    public void run() { 
     System.out.println(Thread.currentThread().getName()); 
    } 
}); 
0

代码的最后一行在主线程中运行。如果要打印正在运行的线程的名称,则必须将打印输出登录到线程中。

尝试以下:

Thread t=new Thread(new Runnable() { public void run() {System.out.println(Thread.currentThread().getName()); } }); 
System.out.println(t.getName()); 
System.out.println(Thread.currentThread().getName()); 
t.start(); 
//System.out.println(Thread.currentThread().getName()); 
+0

你能解释为什么在第二行t.getName()打印主要? –

+0

结果应该如下。 1. t.getName()打印'线程-0'。 2. Thread.currentThread()。getName()打印'main'和3. t.start()启动线程并调用run()方法并打印'Thread-0'。 结果:Thread-0 main Thread-0 – Raymond

+0

好的。非常感谢 –

0

见注释进行说明:

class SimpleThreading 
{ 
    public static void main(String... args) // main thread starts. 
    { 
     Thread t=new Thread(); // new thread object is created. (This is similar to any other java object). No thread created yet. 
     System.out.println(t.getName()); // Prints the default name 
     System.out.println(Thread.currentThread().getName()); // This line is executed by main thread. hence prints main 
     t.start(); // Now, thread is created in runnable state 
     System.out.println(Thread.currentThread().getName()); // This line is executed by main thread. hence prints main 
    } 
} 
相关问题