温馨提示×

如何在Java中创建多线程

小樊
84
2024-07-25 04:59:11
栏目: 编程语言

在Java中,可以通过继承Thread类或实现Runnable接口来创建多线程。下面分别介绍两种方法:

  1. 继承Thread类:
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. 实现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();
    }
}

以上是两种最常见的创建多线程的方式,可以根据具体需求选择合适的方法。

0