温馨提示×

java启动线程的方式有哪些

小亿
90
2023-12-15 15:51:37
栏目: 编程语言

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

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

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

0