在Java中,创建线程有两种主要方法:
- 继承Thread类
- 实现Runnable接口
下面是两种方法的示例:
方法1:继承Thread类
// 创建一个名为MyThread的类,继承自Thread类
class MyThread extends Thread {
    @Override
    public void run() {
        // 在这里编写你的线程代码
        System.out.println("线程正在运行...");
    }
}
public class Main {
    public static void main(String[] args) {
        // 创建MyThread对象
        MyThread myThread = new MyThread();
        // 启动线程
        myThread.start();
    }
}
方法2:实现Runnable接口
// 创建一个名为MyRunnable的类,实现Runnable接口
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 在这里编写你的线程代码
        System.out.println("线程正在运行...");
    }
}
public class Main {
    public static void main(String[] args) {
        // 创建MyRunnable对象
        MyRunnable myRunnable = new MyRunnable();
        // 创建Thread对象,将MyRunnable对象作为参数传递
        Thread thread = new Thread(myRunnable);
        // 启动线程
        thread.start();
    }
}
另外,从Java 5开始,还可以使用Lambda表达式简化代码:
public class Main {
    public static void main(String[] args) {
        // 使用Lambda表达式创建线程
        Thread thread = new Thread(() -> System.out.println("线程正在运行..."));
        // 启动线程
        thread.start();
    }
}
以上就是在Java中创建线程的三种方法。

 便宜VPS测评
便宜VPS测评











