Write a Java Program to Implement Multithreading
Multithreading in Java:
Multithreading is a programming language concept in which a program or process is divided into two or more subprograms that are executed at the same time in parallel. It is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer.
Java Program to Implement Multithreading:
class MyThread implements Runnable{ String name; Thread t; MyThread(String thrdname){ name = thrdname; t= new Thread(this, name); System.out.println("New Thread:" +t); t.start(); } public void run() { try{ for(int i=7;i>0;i--){ System.out.println(name +": " +i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println(name+" interrupted."); } System.out.println(name+" existing."); } } class Thread{ public static void main(String args[]){ MyThread obj1 = new MyThread("One"); MyThread obj2 = new MyThread("Two"); MyThread obj3 = new MyThread("Three"); System.out.println("Thread One is alive: "+obj1.t.isAlive()); System.out.println("Thread Two is alive: "+obj2.t.isAlive()); System.out.println("Thread Three is alive: "+obj3.t.isAlive()); try{ System.out.println("Waiting for threads to finish."); obj1.t.join(); obj2.t.join(); obj3.t.join(); } catch(InterruptedException e){ System.out.println("Main Thread Interrupted"); } System.out.println("Thread One is alive: "+obj1.t.isAlive()); System.out.println("Thread Two is alive: "+obj2.t.isAlive()); System.out.println("Thread Three is alive: "+obj3.t.isAlive()); System.out.println("Main Thread Existing"); } }