learn2code

What is Thread in Java : How They Work and Why You Need Them

thread in java

What is Thread in Java, it’s useful to first have a basic understanding of the segments of memory in RAM that a program uses. Typically, a program’s memory is divided into four segments:

Code Segment :

  • This part of memory contains the executable instructions of a program.
  • It is usually read-only to prevent accidental modification of instructions.
  • All threads of a process share this segment.

Stack Segment:

  • The stack segment is used stores local variables, Methods parameters, return addresses, and the call stack.

Each thread in a process has its own stack segment to maintain its own function call history and local variables.

class Class2 {
    public void method1() {
        // Print numbers from 1 to 20 with a delay of 3 seconds between each number
        for (int i = 1; i <= 20; i++) {
            System.out.print(i + " ");
            try {
                Thread.sleep(300); // Delay for 3000 milliseconds (3 seconds)
            } catch (InterruptedException e) {
                
            }
        }
        System.out.println(); // Print a new line after printing numbers
    }

    public void method2() {
        // Print numbers from 21 to 40 with a delay of 3 seconds between each number
        for (int i = 21; i <= 40; i++) {
            System.out.print(i + " ");
            try {
                Thread.sleep(300); // Delay for 3000 milliseconds (3 seconds)
            } catch (InterruptedException e) {
                
            }
        }
       
        System.out.println(); // Print a new line after printing number
    }
}

public class Class1 {
    public static void main(String[] args) {
        Class2 obj = new Class2();
        
        // Call method1 from Class2
        
        obj.method1();
        obj.method2();
    }
}

The provided program defines 2 classes, Class1 and Class2, and it shows a simple use case where methods from Class2 are invoked sequentially to print numbers with a delay. Here is a detailed explanation of the program:

Class2

Class2 contains two methods, method1 and method2, each responsible for printing a sequence of numbers with a delay in milliscounds.

method1():

  • This method prints numbers from 1 to 20.
  • Each number is followed by a space.
  • After printing each number, the method pauses for 300 milliseconds (not 3 seconds, as mentioned in the comments; 300 milliseconds is 0.3 seconds).
  • The delay is implemented using Thread.sleep(300).
  • If an InterruptedException occurs during the sleep, it is caught and ignored.
  • After printing the sequence, a newline character is printed to move to the next line.

method2():

  • This method prints numbers from 21 to 40.
  • The behavior is similar to method1(), including the delay and exception handling.
  • After printing the sequence, a newline character is printed.

Class1

Class1 contains the main method, which is the entry point of the program.

main():

  • An instance of Class2 is created (obj).
  • method1 of the Class2 instance (obj) is called, which prints numbers from 1 to 20.
  • After method1 completes, method2 of the Class2 instance (obj) is called, which prints numbers from 21 to 40.

Want to make cool text designs in Java? Learn 10 Pattern Programs Now!

Execution Flow

Creating an Instance of Class2:

  • Class2 obj = new Class2();
  • An object obj of Class2 is created.

Calling method1():

  • obj.method1();
  • This prints numbers from 1 to 20 with a delay of 300 milliseconds between each number.

Calling method2():

  • obj.method2();
  • This prints numbers from 21 to 40 with a delay of 300 milliseconds between each number.

Example Output

The program will produce the following output with a delay of 300 milliseconds between each number:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 3 32 33 34 35 36 37 38 39 40
  • Stack grows & shrinks as functions are called and return.

Heap Segment:

  • The heap is used for dynamic memory allocation. This means that memory can be allocated, deallocated at runtime using functions.
  • The heap is shared among all threads within a process.
  • It is typically larger and more flexible than the stack but requires manual management.

Feeling stuck with Java loops? Conquer the for Each Loop with our beginner-friendly guide and write cleaner, more efficient code. Click here to learn!

For more interview theory questions, follow this link!

Thread in Java – FAQs

FAQs: Thread in Java

1. What is a Thread in Java?

A Java thread is the smallest unit of a process that can be executed concurrently. It allows your program to handle multiple tasks at the same time, making it more efficient and responsive.

2. How do you create a Thread in Java?

There are two main ways to create a thread:

  • Extending the Thread class: This approach lets you define the thread’s behavior directly in the run() method of your subclass.
  • Implementing the Runnable interface: This approach provides more flexibility by allowing you to create a separate class containing the thread’s logic. You then pass this class as an argument to the Thread constructor.

3. What’s the difference between start() and run() methods?

– start(): This method initiates the thread’s execution. It schedules the thread to run on the CPU and calls the run() method internally. – run(): This method contains the actual code that the thread executes. Calling run() directly won’t create a new thread; it will simply run the code in the current thread.

Leave a Reply

Harish

Typically replies within a hours