Answer
Multithreading in Java
Method 1: Extending Thread Class
Java
public class MyThread extends Thread {
private String threadName;
MyThread(String name) {
this.threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " → count: " + i);
try {
Thread.sleep(100); // pause 100ms
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
System.out.println(threadName + " finished.");
}
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
t1.start(); // starts new OS thread and calls run()
t2.start(); // t1 and t2 run concurrently
}
}
Sample Output (order varies each run)
CODE
Thread-1 → count: 1
Thread-2 → count: 1
Thread-1 → count: 2
Thread-2 → count: 2
...
Method 2: Implementing Runnable (Preferred)
Java
public class RunnableDemo implements Runnable {
private String name;
RunnableDemo(String name) { this.name = name; }
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(name + ": step " + i +
" [Thread: " + Thread.currentThread().getName() + "]");
}
}
public static void main(String[] args) {
Runnable task1 = new RunnableDemo("LoginTest");
Runnable task2 = new RunnableDemo("CheckoutTest");
Thread t1 = new Thread(task1, "Browser-1");
Thread t2 = new Thread(task2, "Browser-2");
t1.start();
t2.start();
// Wait for both threads to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All tests completed");
}
}
Method 3: Lambda Runnable (Java 8+)
Java
Thread t1 = new Thread(() -> {
System.out.println("Running in: " + Thread.currentThread().getName());
}, "TestThread-1");
t1.start();
Thread vs Runnable
| Thread | Runnable | |
|---|---|---|
| Inheritance | Extends Thread (single inheritance limit) | Implements interface (flexible) |
| Preferred | Less preferred | Preferred |
| Lambda | No | Yes (() -> {}) |
ThreadLocal — For Parallel Selenium Tests
Java
// Each thread gets its OWN driver — no sharing
public class DriverManager {
private static final ThreadLocal<WebDriver> driver = new ThreadLocal<>();
public static void setDriver(WebDriver d) { driver.set(d); }
public static WebDriver getDriver() { return driver.get(); }
public static void quit() { driver.get().quit(); driver.remove(); }
}
// Thread 1 uses its own Chrome instance
// Thread 2 uses its own Firefox instance
// No interference between parallel tests
Automation Testing Relevance
ThreadLocal WebDriver is the foundation of parallel Selenium execution in TestNG parallel suites and Cucumber parallel runners.
