In Java, a Thread
is a class that represents a separate execution thread within a Java program. A Thread
can be created by extending the Thread
class and overriding the run
method, or by implementing the Runnable
interface and passing an instance of the implementing class to a Thread
constructor.
Here's an example of how you can create a Thread
by implementing the Runnable
interface:
public class MyThread implements Runnable { public void run() { // code to be executed by the thread } } // create an instance of MyThread MyThread myThread = new MyThread(); // create a new Thread and pass the instance of MyThread to the constructor Thread thread = new Thread(myThread); // start the thread thread.start();
In this example, the MyThread
class implements the Runnable
interface and overrides the run
method. An instance of MyThread
is then passed to the Thread
constructor, and the start
method is called to start the thread.
The run
method is the entry point for the thread, and it contains the code that will be executed by the thread when it is started.
It's important to note that the Thread
class and the Runnable
interface are part of the java.lang
package and are included in the standard Java distribution. You do not need to import any additional libraries to use them.