1) 自定义一个类Demo,使其实现Runnable接口。 2) 在Demo类中覆写run()方法,在方法编写一个for循环,循环体内打印:当前线程名称:+当前循环次数。 3) 编写测试类Example02,在Example02类的main()方法中,创建一个Demo对象,利用Thread(Runnable target)构造方法创建2个线程对象,分别命名为“蜘蛛侠”和“钢铁侠”,并执行线程对象的start()方法,同时编写for循环,循环内打印“main:”+当前循环次数。
时间: 2023-05-12 20:06:54 浏览: 249
1) 以下是自定义的Demo类,实现了Runnable接口:
```
public class Demo implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("当前线程名称:" + Thread.currentThread().getName() + " 当前循环次数:" + i);
}
}
}
```
2) 在Demo类中覆写了run()方法,并编写了一个for循环,循环体内打印了当前线程名称和当前循环次数。
3) 编写了测试类Example02,创建了一个Demo对象,并利用Thread(Runnable target)构造方法创建了两个线程对象,分别命名为“蜘蛛侠”和“钢铁侠”,并执行了线程对象的start()方法。同时,在Example02类的main()方法中,编写了一个for循环,循环内打印了“main:”和当前循环次数。
```
public class Example02 {
public static void main(String[] args) {
Demo demo = new Demo();
Thread thread1 = new Thread(demo, "蜘蛛侠");
Thread thread2 = new Thread(demo, "钢铁侠");
thread1.start();
thread2.start();
for (int i = 1; i <= 10; i++) {
System.out.println("main:" + i);
}
}
}
```
以上是完整的代码,可以直接运行。