//Create a second thread.
class NewThread2 implements Runnable {
Thread t;
NewThread2() {
// 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);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo2 {
public static void main(String args[]) {
new NewThread2(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} 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.
我有一个问题,当子线程建立以后,调用start()方法,再调用run方法,怎么不先执行了run中的第一个for循环,然后sleep(00),再切换到主线程当中来,执行主线程中的第一次for循环, 而是还没有运行子进程的第一次for循环,然后就跳转到主循环中,就开始执行了。这是怎么回事情?哪位能给解释一下。
class NewThread2 implements Runnable {
Thread t;
NewThread2() {
// 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);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo2 {
public static void main(String args[]) {
new NewThread2(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} 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.
我有一个问题,当子线程建立以后,调用start()方法,再调用run方法,怎么不先执行了run中的第一个for循环,然后sleep(00),再切换到主线程当中来,执行主线程中的第一次for循环, 而是还没有运行子进程的第一次for循环,然后就跳转到主循环中,就开始执行了。这是怎么回事情?哪位能给解释一下。
Chindthread...
仍然是在主线程中。
如果你在
new NewThread2(); // create a new thread
语句后加一句
Thread.Sleep(0); ,
让主线程主动交出自己时间片,运行的结果可能就会是和你想像的一样了。