// 创建一个新的线程有两种常见的方式:继承Thread类或实现Runnable接口。
// 方式一:继承Thread类
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running.");
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();  // 启动线程
    }
}
// 方式二:实现Runnable接口(推荐)
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable task is running.");
    }
}
public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();  // 启动线程
    }
}Thread类的子类,并重写其run()方法来定义线程执行的任务。然后使用start()方法启动线程。Runnable接口的类,并实现其run()方法。这种方式更灵活,因为它不会占用继承的机会(Java不支持多继承),并且可以更好地复用代码。通常推荐使用这种方式。以上两种方式都可以用来创建和启动新的线程。
上一篇:java 并发
下一篇:java修饰符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站