Skip to content

Latest commit

 

History

History
42 lines (27 loc) · 1.54 KB

File metadata and controls

42 lines (27 loc) · 1.54 KB
layout post
title Threads
published false

A Thread in Java means two different things:

  • An instance of class java.lang.Thread
  • A thread of execution

An instance of Thread is just an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack.

In Java, there is one thread per call stack or you can say, one call stack per thread. Even if you don't create any new threads in your program, threads are back there running. The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread.

Create a Thread in Java

Either of the 2 ways:

  • Extend the java.lang.Thread class
  • Implement the Runnable interface

Though extending the Thread class is simple, in real life applications implementing the Runnable interface is the preferred way of creating threads. It's usually not a good OO practice to extend Thread because sub-classing should be reserved for specialized versions of more general superclasses.

So the only time it really makes sense (from an OO perspective) to extend Thread is when you have a more specialized version of a Thread class. In other words, because you have more specialized thread-specific behavior. And if you just want a job to be done by a thread then you should design a class that implements the Runnable interface, which also leaves your class free to extend some other class.

Define a Thread