温馨提示×

java可以创建哪两种线程

小亿
82
2024-09-03 20:58:54
栏目: 编程语言

在Java中,可以创建两种主要类型的线程:

  1. 继承Thread类的线程:通过继承Thread类并重写run()方法来创建一个新的线程。然后,实例化这个子类并调用start()方法来启动新线程。示例代码如下:
class MyThread extends Thread {
    @Override
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
  1. 实现Runnable接口的线程:通过实现Runnable接口并重写run()方法来创建一个新的线程。然后,将Runnable对象传递给Thread类的构造函数,再调用start()方法来启动新线程。示例代码如下:
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

这两种方式都可以用于创建和启动线程,但实现Runnable接口的方式更受推荐,因为它更加灵活,可以避免单继承的局限性。

0