Create three threads (by using Thread class and Runnable interface) where the first thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds.
class NewThread implements Runnable
{
String name,m; // name of thread
int st;
NewThread(String threadname,String msg,int time)
{
name = threadname;
m=msg;
st=time;
Thread t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(i=0;i<10;i++)
{
System.out.println(m);
Thread.sleep(st);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
public class THREAD{
public static void main(String args[])
{
new NewThread("One","Good Morning",1000); // start threads
new NewThread("Two","Hello",2000);
new NewThread("Three","Welcome",3000);
try
{
// wait for other threads to end
//System.out.println("123");
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Comments
Post a Comment