Junior — Middle
What resources and how much time are required to create and launch a new thread of execution?
sobes.tech AI
Answer from AI
Creating and starting a new thread in Java requires certain resources:
- Memory — a separate block of memory is allocated for the thread's stack (usually a few hundred kilobytes, the size can be adjusted).
- Processor time — some time is needed for initializing and starting the thread, including OS scheduling.
- System resources — creating a thread involves system calls, which can be costly when many threads are involved.
Example of creating a thread:
Thread thread = new Thread(() -> {
System.out.println("Thread started");
});
thread.start();
Due to the costs associated with thread creation, thread pools (ExecutorService) are often used to reuse already created threads and reduce overhead.