2014. 11. 29. 05:46

Stop thread using own flag and interrupt method

Here is the sample code that explains how to stop thread using own flag and interrupt method respectively.


public class Main {

	static interface IClosableThread {
		void start();

		void close();
	}

	static class StopThreadUsingFlag extends Thread implements IClosableThread {
		private boolean stopThis = false;

		public void run() {
			try {
				while (this.stopThis == false) {
					System.out.print(".");
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
			}

			System.out.println();
			System.out.println("Finished!");
		}

		public void close() {
			this.stopThis = true;

			try {
				this.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	static class StopThreadUsingInterrupt extends Thread implements
			IClosableThread {
		public void run() {
			try {
				while (!this.isInterrupted()) {
					System.out.print(".");
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
			}

			System.out.println();
			System.out.println("Finished!");
		}

		public void close() {
			this.interrupt();

			try {
				this.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		System.out.println("Hello, Java!");

		IClosableThread thread = new Main.StopThreadUsingFlag();
		thread.start();
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread.close();

		thread = new Main.StopThreadUsingInterrupt();
		thread.start();
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread.close();

	}
}