0 votes
155 views
in Java by
What are the different ways to create thread in java?

1 Answer

0 votes
by (4.4k points)

There are following ways to create thread in java:-

  • To extends Thread class
  • To implements Runnable interface
  • To use ExecutorService

 

Extends Thread class:-

public class MyThreadWithExtends extends Thread{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        System.out.println("Welcome to thread with extends ");
    }
}

Implements Runnable interface:-

public class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        System.out.println("Welcome to thread");
    }
}

Use ExecutorService :- ExecutorService is under the java.util.concurrent pakcage. ExecutorService interface similar to a thread pool.

ExecutorService executorService = Executors.newFixedThreadPool(5);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task to be performed");
    }
});

executorService.shutdown();

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...