Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many ways are for creating a new thread in Java?

Actually, what other ways are available apart from extending the Thread class and implementing the Runnable interface?

like image 310
Ion Ionascu Avatar asked Sep 02 '11 08:09

Ion Ionascu


People also ask

Why are there two ways to create a thread in Java?

Java threads can be created graciously in two ways: implementing the Runnable interface and extending Thread class. Extending the class inherits the methods and data members, fields from the class Tread. In this process only one class can be inherited from the parent class Thread.

How many ways can you create multiple threads in Java?

There are two ways we can create a thread in multithreading in java programs that is by extending thread class and implementing Runnable interface.

Which 2 can be used to create a new thread?

Explanation: There are two ways of creating a thread; extend (sub-class) the Thread class and implement the Runnable interface.


3 Answers

There is exactly one way to create a new thread in Java and that is to instantiate java.lang.Thread (to actually run that thread you also need to call start()).

Everything else that creates threads in Java code falls back to this one way behind the cover (e.g. a ThreadFactory implementation will instantiate Thread objects at some point, ...).

There are two different ways to specify which code to run in that Thread:

  • Implement the interface java.lang.Runnable and pass an instance of the class implementing it to the Thread constructor.
  • Extend Thread itself and override its run() method.

The first approach (implementing Runnable) is usually considered the more correct approach because you don't usually create a new "kind" of Thread, but simply want to run some code (i.e. a Runnable) in a dedicated thread.

like image 61
Joachim Sauer Avatar answered Sep 29 '22 10:09

Joachim Sauer


Threads can be created mainly in 3 different ways

  1. Extend the java.lang.Thread class'

class SampleThread extends Thread {

    //method where the thread execution will start 
    public void run(){
        //logic to execute in a thread    
    }

    //let’s see how to start the threads
    public static void main(String[] args){
       Thread t1 = new SampleThread();
       Thread t2 = new SampleThread();
       t1.start();  //start the first thread. This calls the run() method.
       t2.start(); //this starts the 2nd thread. This calls the run() method.  
    }
} 
  1. Implement the java.lang.Runnable interface

class A implements Runnable{

    @Override
    public void run() {

        // implement run method here 
    }

    public static void main() {
        final A obj = new A();

        Thread t1 = new Thread(new A());

        t1.start();
    }


}
  1. Implement the java.util.concurrent.Callable interface

class Counter implements Callable {

    private static final int THREAD_POOL_SIZE = 2;

    // method where the thread execution takes place
    public String call() {
        return Thread.currentThread().getName() + " executing ...";
    }

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        // create a pool of 2 threads
        ExecutorService executor = Executors
                .newFixedThreadPool(THREAD_POOL_SIZE);

        Future future1 = executor.submit(new Counter());
        Future future2 = executor.submit(new Counter());

        System.out.println(Thread.currentThread().getName() + " executing ...");

        //asynchronously get from the worker threads
        System.out.println(future1.get());
        System.out.println(future2.get());

    }
}

Favor Callable interface with the Executor framework for thread pooling.

The Runnable or Callable interface is preferred over extending the Thread class

like image 26
ankit249 Avatar answered Sep 29 '22 10:09

ankit249


Or you can create a Callable which is an interface which is similar to Runnable except that it defines a method call that can return a value. To instantiante a Callable, you can pass it to an executor. You can find a full explanation of multithreading and callable examples here

like image 39
Dimitri Avatar answered Sep 29 '22 09:09

Dimitri