What Is a Thread? – Core Java

When a modern operating system wants to start running a program, it creates a new process. A process is a program that is currently executing. Every process has at least one thread running within it. Sometimes threads are referred to as lightweight processes. A thread is a path of code execution through a program, and each thread has its own local variables, program counter (pointer to the current instruction being executed), and lifetime. Most modern operating systems allow more than one thread to be running concurrently within a process. When the Java Virtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be spawned (created). 

Normally, you would think of Java code execution starting with the main() method and proceeding in a path through the program until all the statements in main() are completed. This is an example of a single thread. This “main” thread is spawned by the JavaVM, which begins execution with the main() method, executes all the statements in main(), and dies when the main() method completes.

A second thread is always running in the JavaVM: the garbage collection thread. It cleans up discarded objects and reclaims their memory. Therefore, even a simple Java program that only prints Hello World to System.out is running in a multithreaded environment: The two threads are the main thread and the garbage collection thread.

When a Java program includes a graphical user interface (GUI), the JavaVM automatically starts even more threads. One of these threads is in charge of delivering GUI events to methods in the program; another is responsible for painting the GUI window.

For example, imagine that a GUI-based program’s main thread is performing a complex and long-running calculation and that while this is going on, the user clicks a Stop Calculation button. The GUI event thread would then invoke the event handling code written for this button, allowing the calculation thread to be terminated. If only one thread was present, both of these could not be done simultaneously, and interruption would be difficult.

A simple thread example as following:

public class ThreadSample extends Thread {
  public void run() {
    System.out.println("Start one new thread")

  public static void main(String[] args) {
    ThreadSample tt = new ThreadSample();

Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *

  1. joshvelco

    very exciting intorduction for java thread, that’s clear for me to learn this concept, thank you