java线程的创建方式

在Java中,新建线程的方法有两种:

1. 继承`Thread`类并重写`run()`方法

class MyThread extends Thread {
@Override
public void run() {
// 在这里编写线程要执行的任务
}
}

public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}

2. 实现`Runnable`接口并实现`run()`方法

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(); // 启动线程
}
}

 

posted @ 2024-08-02 15:34  HexThinking  阅读(1)  评论(0编辑  收藏  举报