java-thread-4

package Thread_main;

/**
 * 让线程有一个直接死亡的标志 线程对象名.interrupt()
 * ,调用线程类的interrupted方法,
 * 其本质只是设置该线程的中断标志,将中断标志设置为true,并根据线程状态决定是否抛出异常。
 * 因此,通过interrupted方法真正实现线程的中断原理是:
 *  开发人员根据中断标志的具体值,来决定如何退出线程。
   一个简单的实现方式如下:
 *intterupt()使用方法;
 *1.条件:这个线程使用了sleep,或者wait的方法有一个抛出异常InterruptedException
 *2.使用:在其他地方调用intterupt()的方法。这个线程就抛出InterruptedException异常
 *异常之后,在catch配合break,或者return来终止run方法的实现
 */
public class Thread_4 {

	public static void main(String[] args) {

		// TODO 自动生成的方法存根
		System.out.println("--------------");
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO 自动生成的方法存根
				for (int i = 1; i < 10; i++) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						System.out.println("线程1异常中断");
						return;
					
					}
					System.out.println("线程1:		" + i);
				}
			}
		});

		// TODO 自动生成的方法存根

		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {

				// TODO 自动生成的方法存根
				for (int i = 1; i < 20; i++) {
					System.out.println("线程2:" + i);
				
					try {
						Thread.sleep(1000);
						t1.interrupt();//为什么这里的线程没有被中断
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
					}

					
				}
			}

		});
		t1.start();
		t2.start();
	}

}

Supongo que te gusta

Origin blog.csdn.net/huiguo_/article/details/108820517
Recomendado
Clasificación