如何优雅的方式结束线程生命周期

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Qgwperfect/article/details/88745849

 1,第一种方式 通过变量标记

public class ThreadStopGraceful {
	
	private static class Worker extends Thread {
		
		private volatile boolean start = true;
		
		@Override
		public void run() {
			while (start) {
				System.out.println("11111111111111111");
			}
			
			System.out.println("shutdown...");
		}
		
		public void shutdown() {
			this.start = false;
		}
	}

	public static void main(String[] args) {
		Worker worker = new Worker();
		worker.start();
		
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		worker.shutdown();
	}
}

2,第二种方式 通过线程中断

public class ThreadStopGraceful1 {

	private static class Worker extends Thread {
		
		@Override
		public void run() {
			
			/*
			 * 方法1
			 * while(true) {
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					System.out.println(e.getMessage());
					System.out.println("interrupted");
					break; // return
				}
			}*/
			
			
			// 方法2
			while(true) {
				if (Thread.interrupted()) {
					System.out.println("interrupted");
					break; // return
				}
			}
			
			// (2).....接下来的代码
			
			// break  会跳出while 接着往下执行 (2) 处的代码
			// return 会直接返回,不会执行下面 (2) 处的代码
		}
	}
	
	public static void main(String[] args) {
		Worker worker = new Worker();
		worker.start();
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		worker.interrupt();
	}
}

猜你喜欢

转载自blog.csdn.net/Qgwperfect/article/details/88745849