在Java中创建和使用线程,一般有两种方式:继承Thread类和实现Runnable接口。以下是两种方式的示例代码:
- 继承Thread类
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
System.out.println("线程执行中");
}
}
// 创建线程并启动
MyThread thread = new MyThread();
thread.start();
- 实现Runnable接口
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
System.out.println("线程执行中");
}
}
// 创建线程并启动
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
注意:使用Runnable接口创建线程的好处是可以避免单继承的限制。