Explain different ways of creating a thread. Which one would you prefer and why?
Explain different ways of creating a thread. Which one would you prefer and why?
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:
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.
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.
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.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.