如何暴力的方式结束线程生命周期

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

 主类代码:

public class ThreadForceStop {

	private Thread executeThread;
	
	private boolean finished = false;
	
	public void execute(Runnable task) {
		executeThread = new Thread() {
			@Override
			public void run() {
				Thread runner = new Thread(task);
				runner.setDaemon(true);
				runner.start();
				try {
					// 等待runner线程执行结束
					runner.join();
					finished = true;
				} catch (InterruptedException e) {
					System.out.println(e.getMessage());
				}
			}
		};
		
		executeThread.start();
	}
	
	public void shutdown(long mills) {
		long currentTime = System.currentTimeMillis();
		while(!finished) {
			if (System.currentTimeMillis() - currentTime >= mills) {
				System.out.println("任务超时,需要结束!");
				// 中断执行线程,对应子守护线程也会结束
				executeThread.interrupt();
				break;
			}
			
			try {
				Thread.sleep(1);
			} catch (Exception e) {
				System.out.println("执行线程被中断!");
				break;
			}
		}
		
		finished = false;
	}
}

 Main方法:

public class ThreadForceStopMain {
	public static void main(String[] args) {
		/*	
		 * 	方法1:超时结束
			ThreadForceStop threadForceStop = new ThreadForceStop();
			long start = System.currentTimeMillis();
			threadForceStop.execute(()->{
				while(true) {
					
				}
			});
			// 任务超时,结束线程
			threadForceStop.shutdown(10000);
			long end = System.currentTimeMillis();
			System.out.println("耗时为 = " + (end - start));
		 *
		 */	
		
		// 方法2:正常结束
		ThreadForceStop threadForceStop = new ThreadForceStop();
		long start = System.currentTimeMillis();
		threadForceStop.execute(()->{
			try {
				Thread.sleep(5000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		threadForceStop.shutdown(10000);
		long end = System.currentTimeMillis();
		System.out.println("耗时为 = " + (end - start));
	}
}

猜你喜欢

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