What is Java thread


A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

Difference between “implements Runnable” and “extends Thread” in java

In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class.

There has been a good amount of debate on which is better way. Well, I also tried to find out and below is my learning:

1) Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go.

2) Java only supports single inheritance, so you can only extend one class.

3) Instantiating an interface gives a cleaner separation between your code and the implementation of threads.

4) Implementing Runnable makes your class more flexible. If you extend thread then the action you’re doing is always going to be in a thread. However, if you extend Runnable it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application.

5) By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.

6) If you are working on JDK 4 or lesser, then there is bug :

1 comment: