Exercise – 10 (Threads)
a). Write a JAVA program that creates threads by extending Thread class . First thread display"Good Morning " every 1 sec, the second thread displays "Hello"every 2 seconds and the
third display Welcome" every 3 seconds , (Repeat the same by implementing Runnable)
import java.io.*;
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{ }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{ }
}
}
class Threadmsgs
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}
b). Write a program illustrating isAlive and join ()
public class AliveJoin extends Thread
{
public void run()
{
System.out.println("ABDUL KALAM ");
try
{
Thread.sleep(300);
}
catch (InterruptedException ie)
{ }
System.out.println("SUBHASH CHANDRABOSH ");
}
public static void main(String[] args)
{
AliveJoin c1 = new AliveJoin();
AliveJoin c2 = new AliveJoin();
c1.start();
c2.start();
System.out.println(c1.isAlive());
System.out.println(c2.isAlive());
try
{
c1.join(); // Waiting for c1 to finish
}
catch (InterruptedException ie)
{ }
}
}
c). Write a Program illustrating Daemon Threads.
import java.io.*;
public class DaemonThread extends Thread
{
public DaemonThread(String name)
{
super(name);
}
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println(getName() + " is Daemon thread");
}
else
{
System.out.println(getName() + " is User thread");
}
}
public static void main(String[] args)
{
DaemonThread t1 = new DaemonThread("t1");
DaemonThread t2 = new DaemonThread("t2");
DaemonThread t3 = new DaemonThread("t3");
t1.setDaemon(true);
t1.start();
t2.start();
t3.setDaemon(true);
t3.start();
}
}
No comments:
Post a Comment