我能正確實現這些Java線程嗎?目標是有十個併發線程計算從1到(上限22 + i)的總和。我試圖確定名稱並在運行線程時將其打印出來,然後在線程退出時打印結果。目前,我將所有結果以隨機順序同時打印出來,並且我不確定在線程開始和結束時是否正確獲取信息。簡單的併發Java線程 - 捕獲開始和結束
public class threads {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
final int iCopy = i;
new Thread("" + i) {
public void run() {
int sum = 0;
int upperBound = 22;
int lowerBound = 1;
long threadID = Thread.currentThread().getId();
for (int number = lowerBound; number <= upperBound; number++){
sum = sum + number + iCopy;
}
System.out.println(threadID + " thread is running now, I and will compute the sum from 1 to " + (upperBound + iCopy) + ". The i is : " + iCopy);
System.out.println("Thread id #" + threadID + ", the "+ sum + " is done by the thread.");
}
}.start();
}
}
}
不應該從'lowerBound'運行到'upperBound + iCopy',而'sum'應該只是'sum = sum + number'? – isnot2bad 2014-10-27 08:41:36