İşleme için paralel threadler oluşturma
Çok sayıda işlemi (transaction) işlemesi gereken bir finansal analiz uygulaması geliştiriyorsun. Her işlem CPU yoğun hesaplamalar gerektiriyor. Uygulama şu anda sıralı bir yaklaşım kullanıyor ancak bu çok yavaş. Performansı artırmak için çok iş parçacıklı (multi-threaded) bir çözüm uygulamakla görevlendirildin.
Transaction sınıfı senin için önceden yüklendi.
Bu egzersiz, kursun bir parçasıdır
Java'da Kod Optimizasyonu
Egzersiz talimatları
processTransaction()çalıştıracakThreadlar oluştur.- Tüm threadleri başlat.
- Tüm threadlerin tamamlanmasını bekle.
Uygulamalı etkileşimli egzersiz
Bu egzersizi bu örnek kodu tamamlayarak deneyin.
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;
}
}