1. 阅读下列程序,写出运行结果,然后用Runnable接口编写程序来实现同样功能。class SimpleThread extends Thread{ public SimpleThread(String str){ super(str); } public void run(){ for (int i=0;i<10;i++){ System.out.println(i+" "+getName()); try{ sleep((int)(Math.random()*1000)); } catch (InterruptedException e){ } } System.out.println("DONE!"+getName()); } } public class TwoThreadsTest{ public static void main(String args[]){ new SimpleThread("First").start(); new SimpleThread("Second").start(); } }
时间: 2024-02-07 13:03:02 浏览: 64
上述程序的运行结果可能因为随机性而略有不同,但基本上应该是类似于这样:
```
0 First
0 Second
1 First
1 Second
2 First
2 Second
3 First
3 Second
4 First
4 Second
5 First
DONE!First
5 Second
6 Second
DONE!Second
6 First
7 First
7 Second
8 Second
8 First
9 Second
9 First
DONE!Second
DONE!First
```
以下是使用Runnable接口编写的程序:
```
class SimpleRunnable implements Runnable {
private String name;
public SimpleRunnable(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + name);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
System.out.println("DONE!" + name);
}
}
public class TwoThreadsTest {
public static void main(String[] args) {
Thread t1 = new Thread(new SimpleRunnable("First"));
Thread t2 = new Thread(new SimpleRunnable("Second"));
t1.start();
t2.start();
}
}
```
这个程序与上述程序的功能相同,但使用了Runnable接口来实现多线程。注意,由于Runnable接口本身没有start()方法,因此我们需要创建一个Thread对象并将Runnable对象传递给它,然后调用Thread的start()方法来启动线程。
阅读全文