Java Program on Thread Class Methods
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Program 1
package dataflair;
public class MyThread1 extends Thread
{
public void run()
{ int i;
try
{
System.out.println(getName()+" Starts: ");
for (i = 1; i <= 10; i++)
{
System.out.println(getName() + " : "+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(e);
}
System.out.println(getName()+" End: ");
}
}Program 2
package dataflair;
public class MyThread2 extends Thread
{
public void run()
{ int i;
try
{
System.out.println(getName()+" Starts: ");
for (i = 500; i <= 510; i++)
{
System.out.println(getName() + " : "+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(e);
}
System.out.println(getName()+" End: ");
}
}Program 3
package dataflair;
public class TestMain
{
public static void main(String[] args) throws InterruptedException
{
System.out.println("Main Thread Starts: ");
MyThread1 M1=new MyThread1();
MyThread2 M2=new MyThread2();
// System.out.println(M1.getName());
// System.out.println(M2.getName());
M1.setName("First : ");
M2.setName("Second : ");
M1.start();
M2.start();
System.out.println(M1.isAlive()); //true
System.out.println(M2.isAlive()); //true
M1.stop();
//M1.join();
//M2.join();
System.out.println(M1.isAlive()); //false
System.out.println(M2.isAlive());//false
System.out.println("Main Thread End Here: ");
}
}
Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

