多线程学习-day-02理解中断

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

线程基础、线程之间的共享和协作

(目前会将一些概念简单描述,一些重点的点会详细描述)

上一章回顾:

基础概念:

1,CPU核心数,线程数

2,CPU时间片轮转机制

3,什么是进程和线程

4,什么是并行和并发

5,高并发的意义、好处和注意事项

线程基础:

1,启动和终止线程

        ①、三种启动线程方式

本章学习目标:

理解中断

如何安全的终止线程

1,理解中断

        线程自然终止:自然执行完 或 抛出未处理异常

        stop()、resume()、suspend() 三个方法已经在后续的jdk版本已过时,不建议使用

        stop()方法:会导致线程不正确释放资源;

        suspend()方法:挂起,容易导致死锁

        Java线程是协作式工作,而非抢占式工作;

        介绍三种中断方式:

        ①、interrupt()方法

                interrupt()方法中断一个线程,并不是强制关闭该线程,只是跟该线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定;

        ②、inInterrupted()方法

                inInterrupted()方法判断当前线程是否处于中断状态;

        ③、static 方法interrupted()方法

                static方法interrupted()方法判断当前线程是否处于中断状态,并将中断标志位改为false;

        注:方法里如果抛出InterruptedException,线程的中断标志位会被置为false,如果确实需要中断线程,则需要在catch里面再次调用interrupt()方法

public class HasInterruptException {

	// 定义一个私有的Thread集成类
	private static class UseThread extends Thread {

		@Override
		public void run() {
			// 获取当前线程名字
			String threadName = Thread.currentThread().getName();
			// 判断线程是否处于中断标志位
			while (!isInterrupted()) {
				// 测试用interrupt中断后,报InterruptedException时状态变化
				try {
					System.out.println(threadName + "is run !!!!");
					// 设置休眠毫秒数
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// 判断中断后抛出InterruptedException后中断标志位的状态
					System.out.println(threadName + " interrupt flag is " + isInterrupted());
					// 如果抛出InterruptedException后中断标志位置为了false,则需要手动再调用interrupt()方法,如果不调用,则中断标志位为false,则会一直在死循环中而不会退出
					interrupt();
					e.printStackTrace();
				}
				// 打印出线程名称
				System.out.println(threadName);
			}
			// 查看当前线程中断标志位的状态
			System.out.println(threadName + " interrupt flag is " + isInterrupted());
		}
	}

	public static void main(String[] args) throws InterruptedException {
		UseThread useThread = new UseThread();
		useThread.setName("HasInterruptException--");
		useThread.start();
		Thread.sleep(800);
		useThread.interrupt();
	}
}

控制台输出结果:
HasInterruptException--is run !!!!
HasInterruptException-- interrupt flag is false
java.lang.InterruptedException: sleep interrupted
HasInterruptException--
HasInterruptException-- interrupt flag is true
	at java.lang.Thread.sleep(Native Method)
	at com.xiangxue.ch1.safeend.HasInterruptException$UseThread.run(HasInterruptException.java:18)

来自享学IT教育课后总结。

猜你喜欢

转载自blog.csdn.net/Xgx120413/article/details/83046558
今日推荐