Excersise: 9 Suspend, Resume and Threads | Java | Tamizhan Goals

Threads java

Excersise: 9

    Suspend, Resume and Stop Threads (Minimum 3 Threads)

Program


class NewThread implements Runnable
{
	String name;
	Thread t;
	NewThread(String threadname)
	{
		name=threadname;
		t=new Thread(this,name);
		System.out.println("New Thread"+t);
		t.start();
	}
public void run()
{
	try
	{
		for(int i=15;i>0;i--)
		{
			System.out.println(name+":"+i);
			Thread.sleep(200);
		}
	}
	catch(InterruptedException e)
	{
		System.out.println(name+"Interrupted");
	}
	System.out.println(name+"Exiting");
	}
}
class SuspendResume
{
	public static void main(String arg[])
	{
		NewThread ob1=new NewThread("One");
		NewThread ob2=new NewThread("Two");
		try
		{
			Thread.sleep(1000);
			ob1.t.suspend();
			System.out.println("Suspending Thread one");
			Thread.sleep(1000);
			ob1.t.resume();
			System.out.println("Resuming Thread one");
			ob2.t.suspend();
			System.out.println("Suspending Thread two");
			Thread.sleep(1000);
			ob2.t.resume();
			System.out.println("Resuming thread two");
		}
		catch(InterruptedException e)
		{
			System.out.println("Main Thread Interrupted");
		}
		try
		{
			System.out.println("Waiting for threads to finish");
			ob1.t.join();
			ob2.t.join();
		}
		catch(InterruptedException e)
		{
			System.out.println("Main Thread Interrupted");
		}
	System.out.println("Main Thread exiting");
	}
}

Output

Post a Comment

Thanks for your comments. Please be visit and given positive review on our site.

Previous Post Next Post