// Java启动线程的示例代码
// 方法一:继承Thread类
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
System.out.println("线程 " + Thread.currentThread().getId() + " 正在运行");
}
}
public class Main {
public static void main(String[] args) {
// 创建并启动线程
MyThread thread1 = new MyThread();
thread1.start();
// 方法二:实现Runnable接口
Runnable task = () -> {
// 线程执行的任务
System.out.println("线程 " + Thread.currentThread().getId() + " 正在运行(通过Runnable)");
};
// 创建并启动线程
Thread thread2 = new Thread(task);
thread2.start();
}
}
继承 Thread 类:
Thread 类的子类,并重写 run() 方法。main 方法中创建该子类的对象,并调用 start() 方法来启动线程。实现 Runnable 接口:
Runnable 接口的对象,实现 run() 方法。Thread 类的构造函数传入 Runnable 对象,并调用 start() 方法启动线程。这两种方式都可以用来启动线程,但推荐使用 Runnable 接口的方式,因为它不会占用继承的机会(Java 单继承限制),并且更符合面向对象的设计原则。
上一篇:java基本数据类型有哪些
下一篇:java scheduler
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站