java例程练习(多线程[sleep()方法])

import java.util.*;
public class Test {
	public static void main(String[] args) {
		MyThread thread = new MyThread();
		thread.start();
		try {
			Thread.sleep(10000);//主线程睡眠
			
		} catch(InterruptedException e) { }
		
		thread.interrupt();          //-----------不是最好的方法
		//thread.flag = false;       //-----------此方法是终止线程的推荐方法							
		
	}
}

class MyThread extends Thread {
	boolean flag = true;
	public void run() {
		//每隔一秒钟打印一次时间
		while(flag) {
			System.out.println
				("====" + new Date() + "====");
			
			try{
				sleep(1000);
			} catch(InterruptedException e) { //----此异常必须处理
				return;
			}
		}
	}
}

posted on 2012-05-04 23:01  Yours风之恋  阅读(165)  评论(0编辑  收藏  举报