Java 线程创建:继承Thread类和实现Runnable接口
在Java中,有两种方式可以创建线程:
- 继承Thread类并重写run()方法:
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码逻辑
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
- 实现Runnable接口并重写run()方法:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码逻辑
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
}
}
无论使用哪种方式,都需要在run()方法中定义线程要执行的代码逻辑。然后,通过调用Thread类的start()方法来启动线程。
原文地址: https://www.cveoy.top/t/topic/qnwy 著作权归作者所有。请勿转载和采集!