เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสร้าง Thread แบบขนานสำหรับการประมวลผล

คุณกำลังพัฒนาแอปพลิเคชันวิเคราะห์ทางการเงินที่ต้องประมวลผลธุรกรรมจำนวนมาก แต่ละธุรกรรมต้องใช้การคำนวณที่เข้มข้นด้าน CPU แอปพลิเคชันในปัจจุบันทำงานแบบลำดับต่อเนื่อง ซึ่งช้าเกินไป งานของคุณคือนำ multi-threading มาใช้เพื่อเพิ่มประสิทธิภาพการทำงาน

คลาส Transaction ถูกโหลดไว้ให้แล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การปรับแต่งโค้ดใน Java

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง Thread ที่จะรัน processTransaction()
  • เริ่มต้น Thread ทั้งหมด
  • รอให้ 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;
    }
}
แก้ไขและรันโค้ด