class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str); //调用其父类的构造方法
}
public void run() { //重写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();
//第一个线程的名字为First
new SimpleThread("Second").start();
//第二个线程的名字为Second
}
}
运行结果:
0 First
0 Second
1 Second
1 First
2 First
2 Second
3 Second
3 First
4 First
4 Second
5 First
5 Second
6 Second
6 First
7 First
7 Second
8 Second
9 Second
8 First
DONE! Second
9 First
DONE! First
----------------------------------------------------
既然是sleep((int)(Math.random() * 1000));随机产生睡眠时间,那么为什么线程1和2会以固定顺序输出呢?????