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

📄 alternatestop.java

📁 Java Thread Programming (Source
💻 JAVA
字号:
public class AlternateStop extends Object implements Runnable {
	private volatile boolean stopRequested;
	private Thread runThread;

	public void run() {
		runThread = Thread.currentThread();
		stopRequested = false;

		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(2000);
		} catch ( InterruptedException x ) {
			// ignore
		}

		as.stopRequest();
	}
}

⌨️ 快捷键说明

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