threadinterrupt.java

来自「JAVA编程思想源代码 值得一下 很难找的」· Java 代码 · 共 31 行

JAVA
31
字号
package chapter13;

public class ThreadInterrupt extends Thread {
	volatile boolean stop = false; // 共享变量,用于指示线程中断

	public static void main(String args[]) throws Exception {
		ThreadInterrupt thread = new ThreadInterrupt();
		System.out.println("Starting thread...");
		thread.start();
		Thread.sleep(3000);
		System.out.println("Asking thread to stop...");
		thread.stop = true; // 改变共享变量,指示线程中断
		Thread.sleep(3000); // 给一段时间让线程状态变为停止
		if (thread.isAlive()) { // 测试线程是否处在活动中
			System.out.println("The thread is not stopped!");
		} else {
			System.out.println("The thread is stopped!");
		}
	}

	public void run() {
		while (!stop) {
			System.out.println("Thread is running...");
			long time = System.currentTimeMillis();
			while ((System.currentTimeMillis() - time < 1000) && (!stop)) {
			} // 系统时间,每隔一秒而且没有被指示中断则循环一次
		}
		System.out.println("Thread is exiting under request...");
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?