线程阻塞和中断

线程阻塞

所有消耗时间的消耗(耗时操作)

比如:

  • 读取文件
  • 接收用户输入

线程中断

  • 一个线程是一个独立的执行路径,是否结束应有其自身决定
  • 早期的stop是强制结束,已过时
package xc;

public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        Thread t1 = new Thread(new Myrunnable());
t1.start();
        for (int i = 0; i < 5; i++) {
    
    
            System.out.println(Thread.currentThread().getName()+":"+i);
            //在run里不能进行异常的抛出,因为接口没有声明异常的抛出
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
        t1.interrupt();//给线程t1添加中断标记
    }

    static class Myrunnable implements Runnable{
    
    

        @Override
        public void run() {
    
    
            for (int i = 0; i < 10; i++) {
    
    
                System.out.println(Thread.currentThread().getName()+":"+i);
                //在run里不能进行异常的抛出,因为接口没有声明异常的抛出
                try {
    
    
                    Thread.sleep(1000);//进行休眠时会检查是否携带中断标记
                } catch (InterruptedException e) {
    
    //线程中断异常
                    //交代后事
                    System.out.println("发现中断标记");
                    return;//自杀
                }
            }
        }
    }
}

主线程给t1添加中断标记,t1线程在进行以下操作时会检查是否存在标记,若存在,则进入catch块,交代后事

 * @see     java.lang.Object#wait()
 * @see     java.lang.Object#wait(long)
 * @see     java.lang.Object#wait(long, int)
 * @see     java.lang.Thread#sleep(long)
 * @see     java.lang.Thread#interrupt()
 * @see     java.lang.Thread#interrupted()

猜你喜欢

转载自blog.csdn.net/m0_56187876/article/details/115002181