java如何创建一个线程
时间: 2023-10-27 18:17:52 浏览: 45
Java中创建线程有两种方式:继承Thread类和实现Runnable接口。下面分别介绍这两种方式:
1. 继承Thread类
继承Thread类,重写run方法,然后创建Thread对象并调用start方法启动线程。示例代码如下:
```java
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行体
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
```
2. 实现Runnable接口
实现Runnable接口,重写run方法,然后创建Thread对象并将Runnable对象传入Thread构造函数,最后调用start方法启动线程。示例代码如下:
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行体
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
```
两种方式的区别是,继承Thread类的方式是直接使用Thread类的方法和属性,而实现Runnable接口的方式可以方便地实现多个线程共享一个Runnable对象的资源。因此,实现Runnable接口的方式更为常用。