package Thread;
import java.util.Date;
import java.util.Vector;
public class ThreadDemo2 {
public static void main(String[] args) {
Thread thread = new Thread2();// 继续Thread的类可以用向下转型创建,但实现Runnable的类就不能这样了
thread.start();
try {
thread.join();// 等thread线程执行完毕后再继续执行主线程,相当于方法调用,不再是两个线程并行执行
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println("main thread do it");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
return;
}
}
}
}
class Thread2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("time is " + new Date());
try {
sleep(1000);// 因当前类继承了Thread类,而Thread类中有sleep()方法,故可以直接调用,而不需要通过Thread.sleep()
} catch (InterruptedException e) {
return;
}
}
}
}
结果如下:
time is Tue Dec 17 17:17:06 CST 2013
time is Tue Dec 17 17:17:07 CST 2013
time is Tue Dec 17 17:17:08 CST 2013
time is Tue Dec 17 17:17:09 CST 2013
time is Tue Dec 17 17:17:10 CST 2013
time is Tue Dec 17 17:17:11 CST 2013
time is Tue Dec 17 17:17:12 CST 2013
time is Tue Dec 17 17:17:13 CST 2013
time is Tue Dec 17 17:17:14 CST 2013
time is Tue Dec 17 17:17:15 CST 2013
main thread do it
main thread do it
main thread do it
main thread do it
main thread do it
main thread do it
main thread do it
main thread do it
main thread do it
main thread do it
该程序主要是检验join()的用法,主线程等待线程thread执行完毕后再继续执行,相当于传统的方法调用,而不再是两个代码执行流(线程)同时执行。