2016-06-14 2 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 홈페이지 홈페이지메인 스레드 및 현재 스레드

+0

't.start을()'A * 새 * 스레드를 시작합니다. 'main()'메쏘드, 즉 "Main"쓰레드를 실행하는 쓰레드에는 영향을주지 않습니다. – Andreas

답변

2

주요 방법은 Main 스레드에서 실행됩니다. 따라서 t.start() 후뒤에 println 문이 있습니다.

Runnable 인스턴스를 Thread 생성자에 전달하지 않았으므로 두 번째 스레드는 아무것도 수행하지 않습니다. 당신이 Thread 생성자에 Runnable 인스턴스를 전달하고, 그 Runnablerun() 방법은 System.out.println(Thread.currentThread().getName());을 포함 할 경우

, 당신은 Thread-0 인쇄를 볼 수 있습니다.

자바 (8)을 사용하는 경우 예를 들어, 당신이

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

Thread t=new Thread(); 

대체 할 수 있습니다 또는 당신이 같은 논리를 쓸 수 있습니다 사전에 자바 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()이 Main ???을 인쇄하는 이유를 설명 할 수 있습니까? –

+0

결과는 아래와 같아야합니다. 1. t.getName() print 'Thread-0'. 2. Thread.currentThread(). getName() print 'main'3. t.start()는 스레드를 시작하고 run() 메소드를 호출하고 'Thread-0'을 인쇄합니다. 결과 : 스레드 -0 주 스레드 -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 
    } 
}