线程demo2

来源:互联网 发布:mac air windows10 编辑:程序博客网 时间:2024/05/17 10:43
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 {@Overridepublic 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 2013time is Tue Dec 17 17:17:07 CST 2013time is Tue Dec 17 17:17:08 CST 2013time is Tue Dec 17 17:17:09 CST 2013time is Tue Dec 17 17:17:10 CST 2013time is Tue Dec 17 17:17:11 CST 2013time is Tue Dec 17 17:17:12 CST 2013time is Tue Dec 17 17:17:13 CST 2013time is Tue Dec 17 17:17:14 CST 2013time is Tue Dec 17 17:17:15 CST 2013main thread do itmain thread do itmain thread do itmain thread do itmain thread do itmain thread do itmain thread do itmain thread do itmain thread do itmain thread do it

该程序主要是检验join()的用法,主线程等待线程thread执行完毕后再继续执行,相当于传统的方法调用,而不再是两个代码执行流(线程)同时执行。

0 0