// 创建线程的方式一:继承Thread类
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
System.out.println("线程正在运行");
}
}
public class Main {
public static void main(String[] args) {
// 创建线程对象
MyThread myThread = new MyThread();
// 启动线程
myThread.start();
}
}
// 创建线程的方式二:实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
System.out.println("线程正在运行");
}
}
public class Main {
public static void main(String[] args) {
// 创建Runnable对象
MyRunnable myRunnable = new MyRunnable();
// 将Runnable对象传递给Thread构造函数
Thread thread = new Thread(myRunnable);
// 启动线程
thread.start();
}
}
Thread
类并重写run()
方法来定义线程任务。创建线程对象后,调用start()
方法启动线程。Runnable
接口并实现run()
方法来定义线程任务。将Runnable
对象传递给Thread
构造函数,然后调用start()
方法启动线程。这两种方式都可以用来创建和启动线程,选择哪种方式取决于具体的应用场景和个人偏好。
上一篇:java 空格转义字符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站