在Java中,有两种方法可以创建多线程:1. 继承`Thread`类:创建一个类,继承自`Thread`类,并重写`run()`方法
在Java中,有两种方法可以创建多线程:
1. 继承`Thread`类:创建一个类,继承自`Thread`类,并重写`run()`方法,将线程执行的代码放在`run()`方法中。然后创建该类的实例,调用`start()`方法启动线程。
```java
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
```
2. 实现`Runnable`接口:创建一个类,实现`Runnable`接口,并重写`run()`方法,将线程执行的代码放在`run()`方法中。然后创建该类的实例,作为参数传递给`Thread`类的构造函数,调用`start()`方法启动线程。
```java
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
```
无论是继承`Thread`类还是实现`Runnable`接口,都需要将线程执行的代码放在`run()`方法中。`start()`方法会启动线程,并自动调用`run()`方法。
--结束END--
本文标题: java怎么创建多线程
本文链接: https://www.lsjlt.com/news/369411.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-11
2024-05-11
2024-05-11
2024-05-11
2024-05-11
2024-05-11
2024-05-11
2024-05-11
2024-05-11
2024-05-11
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0