BaşlayınÜcretsiz başlayın

Toplu işleme için bir iş parçacığı havuzu uygulama

Aynı anda birden çok belgeyi işlemek zorunda olan bir belge işleme sistemi geliştirdiğini hayal et. Her belge, paralel yapılması gereken yoğun bir işlem gerektiriyor; ancak sistemin aşırı yüklenmesini önlemek için eşzamanlı işlem sayısını sınırlamak istiyorsun. İş yükünü verimli şekilde yönetmek için ExecutorService kullanarak bir çözüm uygulayacaksın.

Bu egzersiz, kursun bir parçasıdır

Java'da Kod Optimizasyonu

Kursa Göz Atın

Egzersiz talimatları

  • 3 iş parçacığından oluşan sabit bir iş parçacığı havuzu oluştur.
  • processDocument(doc) yöntemini yürütücüye bir görev olarak gönder.
  • Yürütücüyü, anında zorla sonlandırmadan kapat.

Uygulamalı etkileşimli egzersiz

Bu egzersizi bu örnek kodu tamamlayarak deneyin.

public class DocumentProcessor {
    public static void main(String[] args) throws InterruptedException {
        List documents = List.of("Doc1", "Doc2", "Doc3", "Doc4", "Doc5");
        List> futures = new ArrayList<>();
        
        // Create a fixed thread pool with 3 threads
        ExecutorService executor = Executors.____(____);

        for (String doc : documents) {
            // Submit the processDocument() method to the executor
            futures.add(executor.submit(() -> ____(____)));
        }
        
        // Shutdown the executor and wait for termination
        executor.____();
        executor.awaitTermination(10, TimeUnit.SECONDS);
        
        try {
            for (Future future : futures) {
                System.out.println(future.get());
            }
        } catch (ExecutionException e) {
            System.out.println("Error processing documents: " + e.getMessage());
        }
    }

    private static String processDocument(String docId) throws InterruptedException {
        System.out.println("Processing " + docId + " on thread " + Thread.currentThread().getName());
        Thread.sleep((long) (Math.random() * 1000));
        return docId + " Processed";
    }
}
Kodu Düzenle ve Çalıştır