// 创建线程的两种方式:继承Thread类和实现Runnable接口
// 1. 继承Thread类
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " running, count: " + i);
}
}
}
// 2. 实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " running, count: " + i);
}
}
}
public class JavaThreadExample {
public static void main(String[] args) {
// 使用继承Thread类的方式创建并启动线程
MyThread thread1 = new MyThread();
thread1.start();
// 使用实现Runnable接口的方式创建并启动线程
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}
Thread类的子类,并重写其run方法来定义线程的行为。然后创建该子类的实例并调用start()方法启动线程。Runnable接口的类,并实现其run方法来定义线程的行为。然后将该类的实例传递给Thread类的构造函数,再调用start()方法启动线程。这两种方式都可以用来创建和启动线程,但通常推荐使用实现Runnable接口的方式,因为它不会占用额外的类继承资源(Java不支持多继承),并且更符合面向对象设计中的单一职责原则。
上一篇:java equals
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站