🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The Thread.start() method in Java is used to start the execution of a thread.
Table of Contents
- Introduction
start()Method Syntax- How
start()Works - Examples
- Basic Usage
- Starting Multiple Threads
- Incorrect Usage: Calling
run()Instead ofstart()
- Real-World Use Case
- Conclusion
Introduction
The Thread.start() method is used to begin the execution of a new thread. When a thread is started using the start() method, the Java Virtual Machine (JVM) invokes the thread's run() method. This creates a new thread of execution, separate from the main thread.
start() Method Syntax
The syntax for the start() method is as follows:
public synchronized void start()
Throws:
IllegalThreadStateExceptionif the thread was already started.
How start() Works
When the start() method is called, the JVM creates a new thread and invokes the run() method of the Thread object. This allows the run() method to execute concurrently with other threads. If the start() method is called more than once on the same thread, an IllegalThreadStateException is thrown.
Examples
Basic Usage
To demonstrate the basic usage of start(), we will create a thread by extending the Thread class and starting it.
Example
public class StartExample extends Thread {
@Override
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
StartExample thread = new StartExample();
thread.start(); // This will start the thread and call the run() method
}
}
Output:
Thread is running...
Starting Multiple Threads
You can create and start multiple threads to perform concurrent tasks.
Example
public class MultipleThreadsExample {
public static void main(String[] args) {
Runnable task = () -> {
System.out.println(Thread.currentThread().getName() + " is running...");
};
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
Thread thread3 = new Thread(task, "Thread-3");
thread1.start();
thread2.start();
thread3.start();
}
}
Output:
Thread-1 is running...
Thread-2 is running...
Thread-3 is running...
(Note: The exact order of output lines may vary due to the nature of multi-threading and thread scheduling.)
Incorrect Usage: Calling run() Instead of start()
If you call the run() method directly instead of start(), the run() method will execute in the current thread, not in a new thread.
Example
public class DirectRunExample extends Thread {
@Override
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
DirectRunExample thread = new DirectRunExample();
thread.run(); // This will call the run() method in the main thread, not a new thread
}
}
Output:
Thread is running...
Correct Usage: Calling start() to Begin a New Thread
To start a new thread, you should call the start() method.
Example
public class CorrectStartExample extends Thread {
@Override
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
CorrectStartExample thread = new CorrectStartExample();
thread.start(); // This will start the thread and call the run() method in a new thread
}
}
Output:
Thread is running...
Real-World Use Case
Concurrent Processing
In real-world scenarios, starting multiple threads can be used for concurrent processing, such as handling multiple client requests in a server application or performing background tasks.
Example
public class ServerApplicationExample {
public static void main(String[] args) {
Runnable clientHandler = () -> {
System.out.println(Thread.currentThread().getName() + " is handling client request...");
try {
Thread.sleep(2000); // Simulate request processing
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + " has completed handling client request.");
};
for (int i = 1; i <= 5; i++) {
Thread thread = new Thread(clientHandler, "ClientHandler-" + i);
thread.start();
}
}
}
Output:
ClientHandler-1 is handling client request...
ClientHandler-2 is handling client request...
ClientHandler-3 is handling client request...
ClientHandler-4 is handling client request...
ClientHandler-5 is handling client request...
ClientHandler-1 has completed handling client request.
ClientHandler-2 has completed handling client request.
ClientHandler-3 has completed handling client request.
ClientHandler-4 has completed handling client request.
ClientHandler-5 has completed handling client request.
(Note: The exact order of output lines may vary due to the nature of multi-threading and thread scheduling.)
Conclusion
The Thread.start() method in Java is used to begin the execution of a new thread by invoking the run() method. By understanding how to use this method, you can manage thread execution effectively and perform concurrent tasks in your Java applications. Whether you are working with single-threaded or multi-threaded environments, the start() method offers used for controlling thread behavior and achieving parallel processing.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment