Javatpoint Logo
Javatpoint Logo

Main thread in Java

The main thread in Java is a crucial component of any Java program. The thread is automatically created when a Java program starts, and maintains the main() method of the application. The main () method, which serves as the program's entrance point, is the initial method utilised at the start of the programme.

The main thread works as a single thread, which means that each line of code is executed sequentially. Other names for this thread are "main application thread" and "main thread".

Any additional threads that the programme may require must be created and started by the main thread. It is also in charge of organising how these threads are carried out and making sure they function effectively.

properties associated with the main thread in Java:

  • Entry point: The main thread acts as the main() method of the program, which is the entry point of the program.
  • Foreground thread: The main thread is a foreground thread, which means that the program will not exit until the main thread finishes its execution.
  • Single thread processing: The primary thread is a single thread processing process, which means it runs sequentially, one line at a time.
  • Higher priority: The main thread has a higher priority than other threads created by the program. It implies that it receives first dibs on system resources like the CPU.
  • System-defined: When a Java program starts, the Java Virtual Machine (JVM) automatically runs the main thread.
  • Can create and initiate additional threads: The main thread controls and initiates any additional threads that the program may need. It is also in charge of organising how these lines will be executed.

How to control Main thread:

In Java, the main thread is automatically created by the Java Virtual Machine (JVM) when a Java program starts. However, you can control the behavior of the main thread by using various methods and techniques provided by the Java language. Here are some ways to control the main thread in Java:

1) Sleep() method:

The main thread's execution can be paused for a set period of time by using the sleep() function. It can be helpful for adding delays or planning when other threads will run.

ALGORITHM:

Step 1: Initialize a variable "sleepTime" to the desired amount of time in milliseconds to pause the execution of the main thread.

Step 2: Call the sleep() method on the main thread and pass the sleepTime value as an argument.

Step 3: The main thread's execution will be paused for the duration set by the sleep() method.

Step 4: After the sleep time has elapsed, the main thread will resume execution and continue with the next statement.

Implementation:

The implementation of above steps given below

FileName: MainThreadSleepExample.java

Output:

Start of main thread
End of main thread

Explanation:

In this example, the main thread is paused for 5 seconds using the sleep() method. The program prints a message at the start of the main thread and another message at the end of the main thread, with a 5-second delay in between.

2) Join()method:

The join() method can be used to delay the execution of the main thread while waiting for other threads to complete. It can be useful for coordinating the execution of multiple threads.

ALGORITHM:

Step 1: Create an instance of the thread that needs to complete before the main thread can continue execution.

Step 2: Now start the thread using the method start().

Step 3: Now we are going to call the join() method on the thread object.

Step 4: The join() method will suspend the execution of the main thread until the thread object finishes processing.

Step 5: After the thread object completes execution, the main thread will resume execution and continue with the next statement.

Implementation:

The implementation of above steps given below

FileName: MainThreadJoin.java

Output:

Start of main thread
Start of other thread
End of other thread
End of main thread

Explanation:

In this example, the main thread creates a new thread and waits for it to complete using the join() method. The new thread simulates some work by pausing for 5 seconds before completing.

3) Interrupt method:

The main thread or additional threads can both be interrupted using the interrupt() technique. It can be useful for implementing thread cancellation or termination.

ALGORITHM:

Step 1: Create an instance of the thread that needs to be interrupted.

Step 2: Now start the thread using the method start().

Step 3: Call the interrupt() method on the thread object to interrupt its execution.

Step 4: When the thread is interrupted then the flag is set to true.

Step 5: To see if the thread is interrupted, check the interrupt flag with the isInterrupted() function.

Step 6: Handle the thread interruption appropriately, such as by gracefully stopping the thread or throwing an exception.

Implementation:

The implementation of above steps given below

FileName: MainThreadInterrupt.java

Output:

Start of main thread
Start of other thread
Doing some work
Doing some work
End of main thread
Thread interrupted
End of other thread

Explanation:

In this example, the main thread creates a new thread and interrupts it after 2 seconds. The new thread simulates some work by printing a message every second until it is interrupted.

4) Using Deadlock Scenario:

A deadlock occurs when two or more threads are awaiting one another's release of an object that has been received. when two or more threads hold locks on different objects and try to obtain locks on objects held by other threads

ALGORITHM:

Step 1: Start the program.

Step 2: In the main method, print a statement indicating that you are entering into a deadlock.

Step 3: Join the current thread to itself.

Step 4: Since the join method will block until the thread it's called on terminates, this will cause a deadlock.

Step 5: The program will be stuck in the deadlock until it's manually terminated.

Step 6: If an InterruptedException is thrown, print the stack trace of the exception.

Step 7: End the program.

Implementation:

The implementation of above steps given below

FileName: DeadlockMain.java

Output:

you are entering into the deadlock

Explanation:

The statement "Thread.currentThread().join()" instructs the main thread to wait for itself to terminate, resulting in a deadlock where the main thread is waiting indefinitely for itself to complete.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA