Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

public class Main {
    public static void main(String[] args) throws Exception {
        Thread previousThread = null;
        for (int i = 0; i < 20; i++) {
            JobRunnable job = new JobRunnable(i, previousThread);
            Thread thread = new Thread(job, "T-" + i);
            thread.start();
            previousThread = thread;
        }
        if (previousThread != null) {
            previousThread.join();
        }
        System.out.println("Program done.");
    }
}

class JobRunnable implements Runnable {
    final int _lineIdx;
    final Thread t;

    public JobRunnable(int lineIdx, Thread threadToWaitForBeforePrinting) {
        _lineIdx = lineIdx;
        t = threadToWaitForBeforePrinting;
    }

    public void run() {
        try {
            String currentThreadName = Thread.currentThread().getName();
            if (t != null) {
                t.join();
            }
            Thread.sleep(3000);
            System.out.println("RESULT: " + _lineIdx + " " + " (Printed on Thread " + currentThreadName + ")");
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
    }
}