Threads

Java makes it easy to define and work with multiple threads of execution within a program .java.lang.Thread is the fundamental thread class in the Java API. There are two ways to define thread. One is to subclass Thread, Override the run() method, and then instantiate your thread subclass. the other is to define a class that implements the runnable method(i.e define a run() method) and passes an instance of this runnable object to the Thread() constructor.

1.Displaying Thread example

import java.util.*;
class Test extends Thread
{ 
public void run()
{ 
for(int i=1;i<5;i++)
{ 
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
} 
System.out.println(i); 
} 
} 
public static void main(String args[]){ 
TestSleepMethod1 t1=new TestSleepMethod1(); 
TestSleepMethod1 t2=new TestSleepMethod1(); 
t1.start(); 
t2.start(); 
} 
} 
 
Output:
 
       1
       1
       2
       2
       3
       3
       4
       4

2.Threading with run() method

import java.util.*;
class TestCallRun2 extends Thread
{ 
public void run()
{ 
for(int i=1;i<5;i++)
{ 
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
} 
System.out.println(i); 
} 
} 
public static void main(String args[])
{ 
TestCallRun2 t1=new TestCallRun2(); 
TestCallRun2 t2=new TestCallRun2(); 
t1.run(); 
t2.run(); 
} 
} 
  
Output:1
       2
       3
       4
       5
       1
       2
       3
       4
       5

Translate »