प्रोसेसिंग के लिए पैरेलल थ्रेड्स बनाना
आप एक फाइनेंशियल एनालिसिस एप्लिकेशन विकसित कर रहे हैं जिसे बहुत बड़ी संख्या में ट्रांज़ैक्शंस प्रोसेस करने हैं. हर ट्रांज़ैक्शन में CPU-इंटेंसिव कैलकुलेशन लगते हैं. अभी एप्लिकेशन सीक्वेंशियल एप्रोच का उपयोग करता है, लेकिन यह काफी धीमा है. आपका काम परफॉर्मेंस बेहतर करने के लिए एक मल्टी-थ्रेडेड सॉल्यूशन लागू करना है.
Transaction क्लास आपके लिए पहले से प्रीलोड की गई है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Java में कोड ऑप्टिमाइज़ करना
अभ्यास निर्देश
- ऐसे
Threadबनाएँ जोprocessTransaction()चलाएँगे. - सभी थ्रेड्स शुरू करें.
- सभी थ्रेड्स के पूरा होने तक प्रतीक्षा करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
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;
}
}