Create Thread
In Java, you can create a new thread by extending the Thread
class or by implementing the Runnable
interface. Here are examples of both methods:
- Extending the
Thread
class:
public class MyThread extends Thread { public void run() { // code to be executed in the new thread } } // create a new thread and start it MyThread thread = new MyThread(); thread.start();
In this example, we define a new class called MyThread
that extends the Thread
class. We override the run()
method to define the code that will be executed in the new thread. We then create a new instance of MyThread
and call the start()
method to start the new thread.
- Implementing the
Runnable
interface:
public class MyRunnable implements Runnable { public void run() { // code to be executed in the new thread } } // create a new thread and start it Thread thread = new Thread(new MyRunnable()); thread.start();
In this example, we define a new class called MyRunnable
that implements the Runnable
interface. We override the run()
method to define the code that will be executed in the new thread. We then create a new instance of MyRunnable
and pass it as an argument to the Thread
constructor. We then call the start()
method to start the new thread.
Note that in both examples, we call the start()
method to start the new thread. This method will create a new thread of execution and call the run()
method to execute the code in the new thread. It's important to note that you should not call the run()
method directly, as this will execute the code in the same thread as the caller, rather than in a new thread.