Thursday, June 17, 2010

Java Interview Question 4

<< Previous                                                                                    Next  >>

Java Interview Question 11:
What is a thread?

A thread can be defined as a separate stream of execution that takes place simultaneously with and independently of everything else that might be happening. A thread runs independently of anything else happening in the computer. Without threads an entire program can be held up by one CPU intensive task or one infinite loop, intentional or otherwise. With threads the other tasks that don't get stuck in the loop can continue processing without waiting for the stuck task to finish.


Java Interview Question 12:
What are the two ways of creating thread and which is the most advantageous method?

There are 2 ways in which a thread can be created.
  • Extend the java.lang.Thread class.
  • Implement the Runnable interface.
Extending java.lang.Thread class

  • Extend the java.lang.Thread class.
  • Override the run() method.
  • Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g.
public class MyThread extends Thread{    
      public void run(){
            // the code that has to be executed in a separate new thread goes here   
      }
      public static void main(String [] args){
            MyThread t = new MyThread();
            t.start();
      }
}

Implementing Runnable interface

The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor, a new thread of execution will be created. e.g.


public class MyRunnable implements Runnable{
    public void run(){
        // the code that has to be executed in a separate new thread goes here
    }
    public static void main(String [] args){
         MyRunnable r = new MyRunnable();
         Thread t = new Thread(r);
         t.start();
     }
}

When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:

  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
  • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.

Java Interview Question 13:
What all constructors are present in the Thread class?

The no-arg constructor in class Thread. 
  •  Thread()
Overloaded constructors in class Thread.

  • Thread(Runnable target)
  • Thread(Runnable target, String name)
  • Thread(String name)

<< Previous                                                                               Next  >>

No comments: