这是一个普通的线程程序
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认证:综合入门第3版”) 作者:Khalid A Mughal,Rolf W Rasmussen)描述了当在线程上调用start方法时它会立即返回。
请解释这一点,为什么在调用start方法时它立即返回并且线程在调用start方法时开始。就像调用start方法一样,它不会调用类的run方法。那么线程什么时候开始呢?
另外解释一下“对start()方法的调用是异步的。”
答案 0 :(得分:1)
您无法直接强制执行/运行哪个Thread。一旦启动它,它就会在较低级别(通常是OS)处理,并且结果可能在不同的机器上甚至在不同的执行中有所不同。如果需要更多控制,则需要使用一些同步机制。
答案 1 :(得分:1)
线程未在start()
的调用下同步启动。它发生在以后(异步)。换句话说,仅仅因为你调用start()
并不意味着线程已经开始。
它们的原因和方式如何,可能取决于JVM和/或OS实现。
答案 2 :(得分:1)
您的整体分析中缺少三件事。