如何在Java中創(chuàng)建多線程

小樊
84
2024-07-25 04:59:11

在Java中,可以通過(guò)繼承Thread類(lèi)或?qū)崿F(xiàn)Runnable接口來(lái)創(chuàng)建多線程。下面分別介紹兩種方法:

  1. 繼承Thread類(lèi):
public class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  1. 實(shí)現(xiàn)Runnable接口:
public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

以上是兩種最常見(jiàn)的創(chuàng)建多線程的方式,可以根據(jù)具體需求選擇合適的方法。

0