【发布时间】:2014-05-01 15:06:25
【问题描述】:
这是一个普通的线程程序
class Counter implements Runnable {
private int currentValue;
public Counter() { currentValue = 0; }
public int getValue() { return currentValue; }
public void run() { // (1) Thread entry point
try {
while (currentValue < 5) {
System.out.println(Thread.currentThread().getName() + ": " + (currentValue++)); // (2) Print thread name.
Thread.sleep(250); // (3) Current thread sleeps.
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println("Exit from thread: " + Thread.currentThread().getName());
}
}
//_______________________________________________________________________________
public class Client {
public static void main(String[] args) {
Counter counterA = new Counter(); // (4) Create a counter.
Thread worker = new Thread(counterA, "Counter A");// (5) Create a new thread.
System.out.println(worker);
worker.start(); // (6) Start the thread.
try {
int val;
do {
val = counterA.getValue(); // (7) Access the counter value.
System.out.println("Counter value read by " + Thread.currentThread().getName()+ ": " + val); // (8) Print thread name.
Thread.sleep(1000); // (9) Current thread sleeps.
} while (val < 5);
} catch (InterruptedException e) {
System.out.println("The main thread is interrupted.");
}
System.out.println("Exit from main() method.");
}
}
输出是
Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.
我的问题是,即使工作线程最初在主线程进入它的 try 块之前启动,主线程执行首先开始,然后当主线程进入睡眠状态时,子线程开始运行。
如这张图片(摘自《Java SCJP 认证程序员指南:综合入门第三版》) 作者:Khalid A Mughal,Rolf W Rasmussen)描述了当线程上的 start 方法被调用时,它立即返回。
请解释这一点,为什么在调用 start 方法时它会立即返回,并且线程是否在调用 start 方法时启动。就像这里调用 start 方法一样,它不会调用类的 run 方法。那么线程实际上是什么时候开始的呢?
还要解释一下“对 start() 方法的调用是异步的。”
【问题讨论】:
标签: java multithreading