Java interrupting a thread that is not alive need not have any effect

@Test
public void interrupt4b() {
	Thread t = new Thread() {
		public void run() {
			for (int i = 0; i < 10; i++) {
				if (isInterrupted()) {
					System.out.println("interrupted");
				} else {
					System.out.println("not interrupted");
				}
			}
			
			interrupt();
			
			for (int i = 0; i < 10; i++) {
				if (isInterrupted()) {
					System.out.println("interrupted");
				} else {
					System.out.println("not interrupted");
				}
			}
		}
	};
	
	t.start();
	
	try {
		t.join();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	// thread t's status is not alive when code executed here.
	System.out.println("the interrupted status while thread's status is not alive:");
	for (int i = 0; i < 10; i++) {
		if (t.isInterrupted()) {
			System.out.println("interrupted");
		} else {
			System.out.println("not interrupted");
		}
	}
	
	if (t.isAlive()) {
		System.out.println("is alive");
	} else {
		System.out.println("is not alive");
	}
	
	for (int i = 0; i < 10; i++) {
		if (t.isInterrupted()) {
			System.out.println("interrupted");
		} else {
			System.out.println("not interrupted");
		}
	}
	
	System.out.println("the interrupted status while thread's status is not alive and call interrupt() to interrupt thread:");
	t.interrupt();
	
	for (int i = 0; i < 10; i++) {
		if (t.isInterrupted()) {
			System.out.println("interrupted");
		} else {
			System.out.println("not interrupted");
		}
	}
}

猜你喜欢

转载自lobin.iteye.com/blog/2395792