// Java 创建线程的两种常见方式:继承 Thread 类和实现 Runnable 接口
// 方式一:继承 Thread 类
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程 " + Thread.currentThread().getName() + " 正在运行");
}
}
public class CreateThreadExample1 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
// 方式二:实现 Runnable 接口
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程 " + Thread.currentThread().getName() + " 正在运行");
}
}
public class CreateThreadExample2 {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
继承 Thread 类:
MyThread
类继承了 Thread
类,并重写了 run()
方法。run()
方法中包含了线程要执行的代码。main
方法中,创建 MyThread
的实例并调用 start()
方法启动线程。实现 Runnable 接口:
MyRunnable
类实现了 Runnable
接口,并实现了 run()
方法。main
方法中,创建 MyRunnable
的实例,并将其传递给 Thread
构造函数,然后调用 start()
方法启动线程。这两种方式都可以用来创建和启动线程,但通常推荐使用实现 Runnable
接口的方式,因为它避免了单继承的限制,更符合面向对象的设计原则。
上一篇:java调用python接口
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站