欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-31 08:35:16
...

 

 

@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");
		}
	}
}