Explain how to create a thread and start it running.
A thread in Java is represented by an object of the Thread class. Implementing threads is achieved in one of two ways:
a) Implementing java.lang.Runnable Interface
b) Extending java.lang.Thread Class
By using one of this ways we can create thread and start it. Both have run () method to run a thread. A class implements the Runnable Interface providing the run () and class extending the Thread class overrides the run () method from the Thread class.
The method implementing the Runnable interface is usually preferred to extending the Thread class for two main reasons:
a) Extending the Thread class means that the subclass cannot extend any other class
b) Inheriting the full overhead of Thread class would be excessive.
Example: To start and run a thread
class counter implements runnable
{
private int currentvalue;
private Thread worker;
public Counter (String threadname)
{
currentvalue=0;
worker=new Thread (this, threadname);
System.out.println (worker);
worker.start();
}
public void run ()
{
try
{
while (currentvalue<5)
{
System.out.println(worker.getName()+ “:” +(currentvalue++));
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(worker.getName()+ “interrupted”);
}
}