Junior — Middle
What are the main classes and tools for implementing multithreading in Java?
sobes.tech AI
Answer from AI
In Java, the following main classes and tools are used for multithreading:
- Thread — the base class for creating and managing threads. You can create a class that extends Thread or pass a Runnable to the constructor.
- Runnable — a functional interface with the run() method that implements the thread's code.
- Executor and ExecutorService — interfaces and classes from the
java.util.concurrentpackage for managing thread pools and asynchronous task execution. - Future and Callable — allow running tasks that return a result and can throw exceptions.
- Synchronized, Lock, ReentrantLock — synchronization mechanisms for managing access to shared resources.
- Concurrent Collections (e.g., ConcurrentHashMap) — collections safe for multithreaded access.
Example of creating and starting a thread with Runnable:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}