温馨提示×

java创建多个子线程的方法是什么

小亿
82
2024-05-31 19:47:08
栏目: 编程语言

Java创建多个子线程的方法可以通过以下两种方式实现:

  1. 继承Thread类:定义一个类继承Thread类,并重写run()方法,在run()方法中编写线程要执行的逻辑。然后通过创建该类的实例对象,并调用start()方法启动线程。
public class MyThread extends Thread {
    public void run() {
        // 线程要执行的逻辑
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        
        thread1.start();
        thread2.start();
    }
}
  1. 实现Runnable接口:定义一个类实现Runnable接口,并实现run()方法,在run()方法中编写线程要执行的逻辑。然后通过创建该类的实例对象,并将其传递给Thread类的构造方法,再调用start()方法启动线程。
public class MyRunnable implements Runnable {
    public void run() {
        // 线程要执行的逻辑
    }

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

0