阅读量:74
在Java中,可以创建两种主要类型的线程:
- 继承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();
}
}
- 实现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接口的方式更受推荐,因为它更加灵活,可以避免单继承的局限性。