java 如何启动一个线程
时间: 2023-12-29 07:52:44 浏览: 30
Java中可以通过继承Thread类或者实现Runnable接口来启动一个线程。
1. 继承Thread类:
```
public class MyThread extends Thread {
public void run() {
System.out.println("线程已启动");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
```
2. 实现Runnable接口:
```
public class MyRunnable implements Runnable {
public void run() {
System.out.println("线程已启动");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
```
两种方法都需要重写run()方法,在run()方法中编写线程需要执行的代码,然后通过start()方法启动线程。但是,使用实现Runnable接口的方式可以避免单继承的限制,更加灵活。