停止线程的两种方式(异常和Return)

  • Post author:
  • Post category:其他


package ExceptionBreak2;

public class TestMain {

	public static void main(String[] args) throws InterruptedException {
		MyThread mt = new MyThread();
		mt.start();
		
		Thread.sleep(200);
		mt.interrupt();

	}
}



package ExceptionBreak2;

public class MyThread extends Thread {
	private int count;

	public void run() {

		try {
			for (int i = 0; i < 100000; i++) {
				System.out.println(this.isInterrupted());
				System.out.println(i);
				if (this.isInterrupted()) { // 若 为 中断状态则break
					System.out.println(i);
					System.out.println("end");
					throw new Exception();
				}

			}
			System.out.println("over");
		} catch (Exception e) {
			System.out.println("log");
		}
	}

}



2:RETURN  但是一般来说是建议使用异常的方法进行线程的停止 这样 线程会得以向上传播 

package ReturnMethodStopThread;

public class TestMain {

	public static void main(String[] args) throws InterruptedException {
		MyThread mt = new MyThread();
		mt.start();
		Thread.sleep(2000);
		mt.interrupt();
	}
}




package ReturnMethodStopThread;

public class MyThread extends Thread {

	public void run() {
		while (1 == 1) {
			if (this.interrupted()) {
				System.out.println("OVER");
				return;
			}
			System.out.println("Test");
		}

	}
}



版权声明:本文为wangyan199366原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。