// Java开启线程的示例代码
// 方法1:通过继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("线程1正在运行");
}
}
public class Main {
public static void main(String[] args) {
// 创建并启动线程
MyThread thread1 = new MyThread();
thread1.start(); // 调用start()方法来启动线程,而不是直接调用run()
// 方法2:通过实现Runnable接口
Runnable task = () -> {
System.out.println("线程2正在运行");
};
Thread thread2 = new Thread(task);
thread2.start(); // 同样使用start()方法启动线程
// 方法3:通过使用ExecutorService线程池
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
System.out.println("线程3正在运行");
});
executor.shutdown(); // 关闭线程池
}
}
Thread类的子类,并重写run()方法。然后通过调用start()方法来启动线程。Runnable接口并重写run()方法。将Runnable对象传递给Thread类的构造函数,再调用start()方法启动线程。Executors工厂类创建线程池,并使用submit()方法提交任务。线程池会自动管理线程的创建和销毁,适合处理大量短期任务。以上是三种常见的Java开启线程的方式。
上一篇:linux 查看java安装位置
下一篇:java集合排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站