在Java中,可以通过继承Thread类或实现Runnable接口来创建多线程。下面分别介绍两种方法:
- 继承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(); } }
- 实现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(); } }
以上是两种最常见的创建多线程的方式,可以根据具体需求选择合适的方法。