为处理创建并行线程
您正在开发一款金融分析应用,需要处理大量交易。每笔交易都包含耗费 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;
}
}