alternatestop.java

来自「Java Thread Programming (Source」· Java 代码 · 共 45 行

JAVA
45
字号
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 + =
减小字号Ctrl + -
显示快捷键?