Threads PracticePrograms
Threads PracticePrograms
-----------
Creation of thread by extending Thread class
class MyThread extends Thread
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
[Link]("Thread is running: " + i);
try
{
[Link](500);
}
catch (InterruptedException e)
{
[Link](e);
}
}
}
}
Program-2
-----------
Creation of thread by implementing Runnable interface
class MyRunnable implements Runnable
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
[Link]("Thread is running: " + i);
try
{
[Link](500);
}
catch (InterruptedException e) {
[Link](e);
}
}
}
}
Program-3
-----------
Program to demonstrate sleep()
class TestSleepMethod extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
[Link](3000);
}
catch(InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}
public static void main(String args[])
{
TestSleepMethod t1=new TestSleepMethod();
TestSleepMethod t2=new TestSleepMethod();
TestSleepMethod t3=new TestSleepMethod();
[Link]();
[Link]();
[Link]();
}
}
Program-4
-----------
Program to demonstrate getName() and setName()
class TestMultiNaming extends Thread
{
public void run()
{
[Link]("running...");
}
public static void main(String args[])
{
TestMultiNaming t1=new TestMultiNaming();
TestMultiNaming t2=new TestMultiNaming();
[Link]("Name of t1:"+[Link]());
[Link]("Name of t2:"+[Link]());
[Link]();
[Link]();
[Link]("Thread1");
[Link]("After changing Name of t1:"+[Link]());
}
}
Program-5
-----------
Program to demonstrate thread priority
class TestMultiPriority extends Thread
{
public void run()
{
[Link]("running thread name is:"+[Link]().getName());