⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 alternatestop.java

📁 介绍Java多线程编程 有chm格式的电子书及书中源码
💻 JAVA
字号:
public class AlternateStop  implements Runnable {
	private volatile boolean stopRequested;
	private Thread runThread;

	public void run() {
		//runThread用来保存引用(invoke)当前运行于run()中的线程
		stopRequested = false;
		runThread = Thread.currentThread();

		int count = 0;

		while ( !stopRequested ) {
			System.out.println("Running ... count=" + count);
			count++;

			try {
				Thread.sleep(300);
			} catch ( InterruptedException x ) {
				Thread.currentThread().interrupt(); // re-assert interrupt
			}
		}
	}

	public void stopRequest() {
		stopRequested = true;

		if ( runThread != null ) {
			runThread.interrupt();
		}
	}

	public static void main(String[] args) {
		AlternateStop as = new AlternateStop();
		Thread t = new Thread(as);
		t.start();

		try {
			Thread.sleep(3000);
		} catch ( InterruptedException x ) {
			// ignore
		}

		as.stopRequest();
	}
}

⌨️ 快捷键说明

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