实现Runnable接口
标签:Runnable,Thread,int,public,12,2023.5,MyTask,id From: https://www.cnblogs.com/zhangmingmkzj/p/17400865.html另一种实现多线程的方式是实现Runnable接口,需要实现run()方法,并将实现了Runnable接口的对象传递给Thread类的构造函数。
public class RunnableDemo {
public static void main(String[] args) {
// 创建10个线程并启动
for (int i = 0; i < 10; i++) {
Runnable task = new MyTask(i);
Thread thread = new Thread(task);
thread.start();
}
}
}
class MyTask implements Runnable {
private int id;
public MyTask(int id) {
this.id = id;
}
public void run() {
System.out.println("Thread " + id + " is running");
try {
Thread.sleep(1000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}