How to create a thread and start it running.

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”);
         }
}
When should we use an event adapter class?
A listener’s class has to implement Listener interface which means all the methods of the interface must be defined in the class...
Component and container classes in Java
The Component class is found under java.awt package. The container class is the subclass of Component class...
Difference between runtime and plain exception
Runtime Exceptions like out-of-bound array indices, NullPointerException , AirthmeticException are all subclasses of java.lang.RuntimeException class...
Post your comment