Write a program that creates 2 threads – each displaying a message (Pass the message as a parameter to the constructor). The threads should display the messages “Hello I am Thread1” and “Hello I am Thread2” respectively. Also display the thread information as it is running


package lab1;

class RunnableDemo implements Runnable {

private Thread t;

private String threadName;

RunnableDemo(String name) {

threadName = name;

System.out.println("Creating " + threadName);

}

public void run() {

System.out.println("Running " + threadName);

try {

for (int i = 4; i > 0; i--) {

System.out.println("Hello I am " + threadName);

Thread.sleep(50);

}

} catch (InterruptedException e) {

System.out.println("Thread " + threadName + " interrupted.");

}

System.out.println("Thread " + threadName + " exiting.");

}

public void start() {

System.out.println("Starting " + threadName);

if (t == null) {

t = new Thread(this, threadName);

t.start();

}

}

}

public class Ques_1 {

public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo("Thread-1");

R1.start();

RunnableDemo R2 = new RunnableDemo("Thread-2");

R2.start();

}

}


OUTPUT



Post a Comment

0 Comments