java如何创建多线程

895
2024/4/12 14:18:53
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以通过以下方式创建多线程:

  1. 继承Thread类:创建一个新的类并继承Thread类,重写run()方法来定义线程执行的任务。然后创建该类的对象并调用start()方法启动线程。
public class MyThread extends Thread {
    public void run() {
        // 线程执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  1. 实现Runnable接口:创建一个实现了Runnable接口的类,实现run()方法来定义线程执行的任务。然后创建该类的对象,并将其作为参数传递给Thread类的构造方法,最后调用start()方法启动线程。
public class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}
  1. 使用匿名内部类:可以直接在创建Thread对象时使用匿名内部类来实现线程执行的任务。
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            // 线程执行的任务
        });
        thread.start();
    }
}

无论采用哪种方式,创建多线程后,可以通过调用start()方法启动线程,并在run()方法中定义线程执行的任务。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java乐观锁怎么实现