RunnableTask.java Source code

Java tutorial

Introduction

Here is the source code for RunnableTask.java

Source

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class RunnableTask implements Runnable {
    private int taskId;
    private int loopCounter;

    public RunnableTask(int taskId, int loopCounter) {
        this.taskId = taskId;
        this.loopCounter = loopCounter;
    }

    public void run() {
        for (int i = 1; i <= loopCounter; i++) {
            try {
                System.out.println("Task #" + this.taskId + "  - Iteration #" + i);
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println("Task #" + this.taskId + "  has  been  interrupted.");
                break;
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        final int THREAD_COUNT = 3;
        final int LOOP_COUNT = 3;
        final int TASK_COUNT = 5;

        // Get an executor with three threads in its thread pool
        ExecutorService exec = Executors.newFixedThreadPool(THREAD_COUNT);

        // Create five tasks and submit them to the executor
        for (int i = 1; i <= TASK_COUNT; i++) {
            RunnableTask task = new RunnableTask(i, LOOP_COUNT);
            exec.submit(task);
        }
        exec.shutdown();
    }
}