java启动线程的方式有哪些

   2025-02-13 2880
核心提示:Java启动线程的方式有以下几种:继承Thread类并重写run()方法,然后调用start()方法启动线程。public class MyThread extends Th

Java启动线程的方式有以下几种:

继承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();    }}
实现Runnable接口并实现run()方法,然后创建Thread对象并传入实现了Runnable接口的对象,然后调用start()方法启动线程。
public class MyRunnable implements Runnable {    public void run() {        // 线程执行的代码    }}public class Main {    public static void main(String[] args) {        MyRunnable runnable = new MyRunnable();        Thread thread = new Thread(runnable);        thread.start();    }}
使用匿名内部类创建线程对象并重写run()方法,然后调用start()方法启动线程。
public class Main {    public static void main(String[] args) {        Thread thread = new Thread() {            public void run() {                // 线程执行的代码            }        };        thread.start();    }}
使用Lambda表达式创建线程对象并实现run()方法,然后调用start()方法启动线程。
public class Main {    public static void main(String[] args) {        Thread thread = new Thread(() -> {            // 线程执行的代码        });        thread.start();    }}

这些方式都可以创建并启动线程,但使用Runnable接口或Lambda表达式创建线程对象更为常见和灵活,因为Java不支持多重继承,而实现Runnable接口可避免这个限制,并且可以在需要时重用实现了Runnable接口的对象。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言