Creating and Running Threads
In Java, threads are created and run using the Thread
class. To create a new thread, you can extend the Thread
class or implement the Runnable
interface.
Here's an example of creating and running a thread using the Runnable
interface:
1public class Main {
2 public static void main(String[] args) {
3 Thread thread = new Thread(new MyRunnable());
4 thread.start();
5 System.out.println("Main thread is running");
6 }
7}
8
9class MyRunnable implements Runnable {
10 public void run() {
11 System.out.println("New thread is running");
12 }
13}
In this example, we create a class named Main
with a main
method. Inside the main
method, we create a new Thread
object and pass an instance of the MyRunnable
class to it. The MyRunnable
class implements the Runnable
interface, which requires the implementation of the run
method. The run
method contains the code that will be executed when the new thread starts. We then start the new thread using the start
method.
When the program is executed, it will output:
1New thread is running
2Main thread is running
The output shows that the new thread is running concurrently with the main thread. The order of execution between the two threads is determined by the operating system scheduler.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
System.out.println("Main thread is running");
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("New thread is running");
}
}