Junior — Middle
How can a thread of execution be initiated in the JVM using any programming language?
sobes.tech AI
Answer from AI
In JVM, a thread of execution can be initiated in several ways, regardless of the programming language compiled into JVM bytecode. The main methods are:
- Creating and starting a Thread object:
Thread thread = new Thread(() -> {
// code executed in the new thread
System.out.println("Thread started");
});
thread.start();
- Using the Runnable interface:
Runnable task = () -> {
// task code
};
Thread thread = new Thread(task);
thread.start();
- Using ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
// task code
});
executor.shutdown();
- In other JVM languages (e.g., Kotlin):
thread(start = true) {
println("Thread in Kotlin")
}
Thus, to start a thread, you need to define a task (Runnable or lambda) and pass it to a Thread or Executor, then call start() to begin execution.