Junior — Middle
What components or resources are needed to initialize and start a thread of execution?
sobes.tech AI
Answer from AI
The following components are necessary for initializing and starting a thread in Java:
-
A class implementing the thread — this can be a class that extends
Threador implements theRunnableinterface. -
A thread object — an instance of the thread class or a
Runnableobject passed to theThreadconstructor. -
The
start()method — called to start a new thread, which then calls therun()method in a separate thread.
Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // Starting the thread
}
}
Thus, to start a thread, you need to define a task (via Runnable or by extending Thread), create a thread object, and call start().