Câu hỏi phỏng vấn Java
Câu hỏi

Explain different ways of creating a thread. Which one would you prefer and why?

Câu trả lời

To answer the interview question on the different ways of creating a thread in Java and which one to prefer, let's first explore the various methods available:

Different Ways to Create a Thread in Java

  1. Extending the Thread class: This is one of the simplest ways to create a thread. You create a new class that extends Thread and override its run() method. To start the thread, you create an instance of your class and call its start() method[1][3][6][7].

  2. Implementing the Runnable interface: This method involves creating a new class that implements the Runnable interface and then implementing the run() method. You then create an instance of the Thread class, passing your Runnable object to its constructor, and start the thread using the start() method[1][3][6][7][11].

  3. Using the Callable interface and FutureTask: Callable is similar to Runnable but it can return a result and throw a checked exception. You wrap a Callable object in a FutureTask, then create a Thread object with the FutureTask and start it. This method is useful when you need to retrieve a result from your thread[1][5].

  4. Using the ExecutorService: This is a more advanced and flexible way to manage multiple threads. You use an ExecutorService to create a thread pool and submit Runnable or Callable tasks that it handles. The ExecutorService takes care of thread creation, life cycle management, and provides methods for task submission and tracking[1][5].

Preferred Method and Rationale

The preferred method for creating threads can depend on the specific requirements of the application, but generally, using the ExecutorService is often recommended for several reasons:

  • Scalability: ExecutorService manages a pool of threads and optimizes the use of resources. It allows you to control the number of threads being used, which is more efficient than manually managing each thread[1][5].

  • Task Management: It provides convenient methods to manage and monitor tasks, such as submit(), invokeAll(), and `invok...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is the importance of finally block in exception handling?

middle

What is the difference between doGet() and doPost() ?

middle

Explain the life cycle of a Servlet

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào