Shi*_*han 0 java concurrency multithreading
这是一个创建新线程并开始运行的示例:
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);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
Run Code Online (Sandbox Code Playgroud)
现在考虑另一个线程(main),在创建新线程之后,在调用其在Thread中声明的start()方法之前,它不会开始运行.实质上,start()执行对run()的调用.
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(10000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
Run Code Online (Sandbox Code Playgroud)
}
在NewThread的构造函数中,通过以下语句创建一个新的Thread对象:
t = new Thread(this, "Demo Thread");
Run Code Online (Sandbox Code Playgroud)
将此作为第一个参数传递表明您希望新线程在此对象上调用run()方法.接下来,调用start(),它从run()方法开始执行执行的线程.这会导致子线程的for循环开始.在调用start()之后,NewThread的构造函数返回main().当主线程恢复时,它进入for循环.两个线程继续运行,共享CPU,直到它们的循环完成.
在调用start()之后,为什么线程的构造函数返回到main(),而不是将控件转发给run()方法?
| 归档时间: |
|
| 查看次数: |
430 次 |
| 最近记录: |