Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    ExecutorService threads;

    public Main(int poolSize) {
        threads = Executors.newFixedThreadPool(poolSize);
    }

    public void createThread(String name) {
        threads.execute(new MyThread(name)); // Create MyThread
    }

    public static void main(String[] args) {
        Thread t = Thread.currentThread();
        Main t1 = new Main(3);
        t1.createThread("Child 1");
        t1.createThread("Child 2");
        for (int i = 0; i <= 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("The cirrent Thread is " + t.getName() + " and thread ID is " + t.getId());
        }
    }
}

class MyThread extends Thread {
    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i <= 5; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("The current Thread is " + super.getName() + " and thread ID is " + super.getId());
        }
    }
}