Junior — Middle
What methods exist for implementing multithreading in programming?
sobes.tech AI
Answer from AI
In Java, there are several main ways to implement multithreading:
- Thread Class — creating a new thread by inheriting from the Thread class and overriding the run() method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
}
}
MyThread t = new MyThread();
t.start();
- Runnable Interface — implementing the Runnable interface and passing the object to the Thread constructor.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread via Runnable");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
- Executor Framework — using a thread pool to manage and reuse threads.
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task in thread pool"));
executor.shutdown();
-
Callable and Future — for executing tasks that return a result and can throw exceptions.
-
Fork/Join Framework — for parallel processing of large tasks by breaking them into subtasks.
Each method is suitable for different scenarios; the choice depends on the requirements for thread management and task complexity.