スレッドエッセイ-テストsleep

2022 ワード

package test.Thread;

import java.util.Date;

public class testSleep {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread1 t1 = new Thread1();
		t1.start();
		for (int i = 1; i < 5; i++) {
			System.out.println("main thread times :" + i);
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				System.out.println("main thread is interrupted");
			}
		}
		t1.interrupt();
	}
}

class Thread1 extends Thread {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			System.out.println("this is Thread1  " + new Date());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				System.out.println("Thread1 is Interrupted");
				return;
			}
		}
	}

}

 The result:
 
main thread times :1this is Thread1  Fri Sep 05 20:38:25 CST 2008this is Thread1  Fri Sep 05 20:38:27 CST 2008this is Thread1  Fri Sep 05 20:38:28 CST 2008this is Thread1  Fri Sep 05 20:38:29 CST 2008this is Thread1  Fri Sep 05 20:38:30 CST 2008main thread times :2this is Thread1  Fri Sep 05 20:38:31 CST 2008this is Thread1  Fri Sep 05 20:38:32 CST 2008this is Thread1  Fri Sep 05 20:38:33 CST 2008this is Thread1  Fri Sep 05 20:38:34 CST 2008this is Thread1  Fri Sep 05 20:38:35 CST 2008main thread times :3this is Thread1  Fri Sep 05 20:38:36 CST 2008this is Thread1  Fri Sep 05 20:38:37 CST 2008this is Thread1  Fri Sep 05 20:38:38 CST 2008this is Thread1  Fri Sep 05 20:38:39 CST 2008this is Thread1  Fri Sep 05 20:38:40 CST 2008main thread times :4this is Thread1  Fri Sep 05 20:38:41 CST 2008this is Thread1  Fri Sep 05 20:38:42 CST 2008this is Thread1  Fri Sep 05 20:38:43 CST 2008this is Thread1  Fri Sep 05 20:38:44 CST 2008this is Thread1  Fri Sep 05 20:38:45 CST 2008Thread1 is Interrupted