Threadpool

Implementace threadpoolu pomocí ExecutorService.

public class Main {
    private static final int numThreads = 10;
 
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService threadPool;
        threadPool=Executors.newFixedThreadPool(3);
        Runnable tasks[] = new Runnable[numThreads]; 
        for (int i = 0; i < tasks.length; i++) {
            tasks[i]=new MyRunnable(i+1);            
        }
        Future futureResults[] = new Future[numThreads];
        for (int i = 0; i < tasks.length; i++) {
             futureResults[i] = threadPool.submit(tasks[i]);
        }
 
        for (Future futureResult : futureResults) {
            System.out.println("F1:"+futureResult.isDone());
        }
        // vraci null, kdyz je ukonceny beh vlakna
         for (Future futureResult : futureResults) {
            System.out.println("FGet:"+futureResult.get());
        }
 
 
        threadPool.shutdown();
 
 
    }
}

Implementace samotné úlohy pomocí interface Runnable - vlákno jako výsledek nevrací žádnou hodnotu.

import static java.lang.Thread.sleep;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class MyRunnable implements Runnable {
 
    private int countdown;
    private int number;
 
    public MyRunnable(int countdown) {
        this.countdown = countdown;
        this.number=countdown;
    }
 
    @Override
    public void run() {
        System.out.println("Starting thread with counter set on " + countdown);
        for (int i = countdown; i > 0; i--) {
            System.out.println("Thread " + number+ " sleep " +  i);
            try {
                sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyRunnable.class.getName()).log(Level.SEVERE, null, ex);
            }
 
        }
        System.out.println("Thread " + this.number + " finished");
    }
 
}

Implementace samotné úlohy pomocí interface Callable - vlákno jako výsledek vrací definovanou poměnnou.

public class MyCallable implements Callable<String> {
 
    private int countdown;
    private int number;
 
    public MyCallable(int countdown) {
        this.countdown = countdown;
        this.number = countdown;
    }
 
    @Override
    public String call() throws Exception {
        System.out.println("Starting thread with counter set on " + countdown);
        for (int i = countdown; i > 0; i--) {
            System.out.println("Thread " + number + " sleep " + i);
            try {
                sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyCallable.class.getName()).log(Level.SEVERE, null, ex);
            }
 
        }
        return ("Thread " + this.number + " finished");
    }
}

courses/b0b36pjv/tutorials/09/threadpool.txt · Last modified: 2025/04/14 10:37 by mudromar