Exercise 7
Exercise 7
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)
try
{
for (int i=1;i<5;i++ )
{
System.out.println(".............Main Thread ....."+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("........... Main interrupted.........");
}
/* Creating two threads: by default they are
user threads (non-daemon threads)
*/
DaemonThread t1=new DaemonThread();
DaemonThread t2=new DaemonThread();
//Making user thread t1 to Daemon
t1.setDaemon(true);
//starting both the threads
t1.start();
t2.start();
}
}
Output
}
catch (InterruptedException e)
{
System.out.println(".......producer interrupted....");
}
}
sb.notify();
}
}
}
class Consumer extends Thread {
Producer prod;
Consumer(Producer prod) {
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
try
{
prod.sb.wait();
}
catch (InterruptedException e)
{
System.out.println(".......consumer interrupted....");
}
System.out.println(prod.sb);
}
}
}
class InterThreadCommunication
{
public static void main(String[] args)
{
Producer obj1=new Producer();
Consumer obj2=new Consumer(obj1);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t2.start();
t1.start();
}
}
Output