使用Runable接口创建多线程
时间: 2023-12-10 22:05:34 浏览: 175
使用Runnable接口可以创建多线程,具体步骤如下:
1. 实现Runnable接口,并重写run()方法,将需要在多线程中执行的代码放在run()方法中。
```
public class MyRunnable implements Runnable {
@Override
public void run() {
// 需要在多线程中执行的代码
System.out.println(Thread.currentThread().getName() + "正在执行任务");
}
}
```
2. 创建MyRunnable对象,并将其作为参数创建Thread对象。
```
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
```
3. 启动线程。
```
thread.start();
```
完整的示例代码如下:
```
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行任务");
}
}
```
在上述代码中,我们首先创建了一个MyRunnable对象,并将其作为参数创建了一个Thread对象。然后,我们启动了该线程并执行了run()方法中的代码。在执行过程中,我们通过Thread.currentThread().getName()方法获取了当前线程的名字,并输出了一段字符串。
阅读全文
相关推荐

















