Question
Can someone provide a straightforward Java thread example that illustrates simultaneous execution of multiple threads?
public class ThreadExample {
public static void main(String[] args) {
// Create three threads
Thread t1 = new Thread(new Task("Thread 1"));
Thread t2 = new Thread(new Task("Thread 2"));
Thread t3 = new Thread(new Task("Thread 3"));
// Start the threads
t1.start();
t2.start();
t3.start();
}
}
class Task implements Runnable {
private String threadName;
Task(String name) {
this.threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running iteration " + i);
try {
Thread.sleep((int)(Math.random() * 1000)); // Sleep for a random time
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
}
}
Answer
In Java, threading allows multiple threads of execution to run concurrently. This example illustrates the creation of three separate threads, providing a clear demonstration of their simultaneous operation.
public class ThreadExample {
public static void main(String[] args) {
// Create three threads
Thread t1 = new Thread(new Task("Thread 1"));
Thread t2 = new Thread(new Task("Thread 2"));
Thread t3 = new Thread(new Task("Thread 3"));
// Start the threads
t1.start();
t2.start();
t3.start();
}
}
class Task implements Runnable {
private String threadName;
Task(String name) {
this.threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running iteration " + i);
try {
Thread.sleep((int)(Math.random() * 1000)); // Sleep for a random time
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
}
}
Causes
- Threads are independent units of execution and can run concurrently.
- Java's Thread class and Runnable interface facilitate concurrent execution.
Solutions
- Define task logic in a runnable class.
- Instantiate threads with the runnable implementation.
- Use start() method to launch multiple threads.
Common Mistakes
Mistake: Forgetting to start a thread with start() method, using run() instead.
Solution: Always use start() to initiate thread execution.
Mistake: Incorrectly managing thread lifecycle, leading to deadlocks or resource issues.
Solution: Carefully design thread interactions and utilize concurrency controls where necessary.
Helpers
- Java threads example
- Java concurrent execution
- multithreading in Java
- Runnable interface Java
- Java threading tutorial