建立平行執行緒以進行處理
你正在開發一套財務分析應用程式,需要處理大量交易。每筆交易都需要大量 CPU 計算。應用程式目前採用循序方式,但速度太慢。你的任務是實作多執行緒解決方案,以提升效能。
Transaction 類別已為你預先載入。
本練習屬於課程
Java 程式碼最佳化
練習說明
- 建立會執行
processTransaction()的Thread。 - 啟動所有執行緒。
- 等待所有執行緒完成。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class TransactionProcessor {
public static void main(String[] args) throws InterruptedException {
List transactions = generateTransactions(1000);
List threads = new ArrayList<>();
for (int t = 0; t < 4; t++) {
int start = t * 250;
int end = (t == 3) ? transactions.size() : (t + 1) * 250;
// Create thread that will run processTransaction()
Thread thread = new ____(() -> {
for (int i = start; i < end; i++) {
processTransaction(transactions.get(i));
}
});
threads.add(thread);
// Start the thread
thread.____();
}
// Wait for all threads to complete
for (Thread thread : threads) {
thread.____();
}
}
static void processTransaction(Transaction tx) {
double result = 0;
for (int i = 0; i < 1000; i++) {
result += Math.sqrt(tx.amount * i);
}
tx.result = result;
}
static List generateTransactions(int n) {
List list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(new Transaction(Math.random() * 1000));
}
return list;
}
}