论坛首页 编程语言技术论坛

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

浏览 2907 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2017-10-10  

 

 

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

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics