Question
Solution
JAVA
package q18198;
import java.util.Scanner;
class TablePrinter implements Runnable {
private int tableNumber;
public TablePrinter(int tableNumber) {
this.tableNumber = tableNumber;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(tableNumber + " * " + i + " = " + (tableNumber * i));
try {
Thread.sleep(100); // 100ms delay for visualization
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread interrupted: " + Thread.currentThread().getName());
break;
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of tables:");
int numTables = scanner.nextInt();
Thread[] threads = new Thread[numTables];
for (int i = 0; i < numTables; i++) {
threads[i] = new Thread(new TablePrinter(i + 1));
threads[i].start();
}
for (int i = 0; i < numTables; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
Thread.currentThread().interrupt();
}
}
scanner.close();
}
}
2/2 test cases passed
4/4 hidden test cases passed