이 코드를 이해하는 데 문제가 있습니다. 나는 자바에 대한 2 시간의 지식 만 갖고있다. 여기 기본 Java 스레딩 및 실행 가능 패턴
코드입니다 :// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
그리고 여기의 출력 : 여기에
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
내 질문입니다.
코드가 따르는 패턴을 이해하고 싶습니다. 저에 따르면,
- 우선, 프로그램은
main()
기능을 실행하기 시작해야합니다. 따라서 NewThread의 인스턴스를 초기화해야합니다. - 그럼, 내가 NewThread 생성자로 가서 온다) (즉 t.start 후
Child thread: Thread[Demo Thread,5,main]
- 를 작성해야하기 때문에 프로그램
public void run()
에서 (?? 내가 잘못 여기 AM)public void run()
을 실행해야 내가 출력 Child Thread 5
을 얻어야한다고 생각하지만, 대신 Main Thread 5
을 얻었습니다. 나는 왜 궁금해하니 ??
나를 도울 사람이 있습니까 ?? 미리 감사드립니다.
Wonderful : Java threating ... :-) – Seelenvirtuose