Define a thread called “PrintText_Thread” for printing text on command prompt for n number of times. Create three threads and run them. Pass the text and n as parameters to the thread constructor. Example:

First thread prints “I am in FY” 10 times
Second thread prints “I am in SY” 20 times

Third thread prints “I am in TY” 30 times



Package lab1;

import java.util.Scanner;

class PrintText_Thread implements Runnable {

private Thread t;

private String threadName;

private int n;

PrintText_Thread(String name, int num) {

threadName = name;

n = num;

}

public void run() {

try {

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

System.out.println(threadName);

Thread.sleep(50);

}

} catch (InterruptedException e) {

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

}

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

}

public void start() {

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

if (t == null) {

t = new Thread(this, threadName);

t.start();

}

}

}

public class Ques_2 {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the no. of times you want to run thread: ");

int num = sc.nextInt();

sc.close();

PrintText_Thread R1 = new PrintText_Thread("I am in FY", num);

R1.start();

PrintText_Thread R2 = new PrintText_Thread("I am in SY", num);

R2.start();

PrintText_Thread R3 = new PrintText_Thread("I am in TY", num);

R3.start();

}

}

OUTPUT



Post a Comment

0 Comments