乐闻世界logo
搜索文章和话题

How to Create Threads in Java?

2月7日 00:13

There are two primary ways to create threads in Java:

  1. Inheriting the Thread Class:

    • First, define a class that extends Thread.
    • Then, override the run() method in this class and place the code you want the thread to execute inside the run() method.
    • Create an instance of this class that extends Thread and call the start() method on the instance to start the thread.

    Example code:

    java
    class MyThread extends Thread { public void run(){ System.out.println("My thread is running"); } } public class TestThread { public static void main(String args[]) { MyThread t = new MyThread(); t.start(); // Start the thread } }
  2. Implementing the Runnable Interface:

    • Define a class that implements the Runnable interface.
    • Implement the run() method of this interface and place the code you want to run in the thread inside the run() method.
    • Create an instance of this class and pass it as a parameter to the Thread constructor to create a thread object.
    • Call the start() method on the thread object to start the thread.

    Example code:

    java
    class MyRunnable implements Runnable { public void run(){ System.out.println("Thread created via Runnable interface"); } } public class TestRunnable { public static void main(String args[]) { MyRunnable myRunnable = new MyRunnable(); Thread t = new Thread(myRunnable); t.start(); // Start the thread } }

These two methods essentially create a block of code that can run independently, and through the start() method, have the Java Virtual Machine (JVM) call the run() method of this block. Using the Runnable interface is more flexible because Java does not support multiple inheritance; therefore, if your class has already extended another class, you must use the Runnable interface to create threads.

标签:Java