多线程 之 interrupt

interrupt 多线程中 可以中断 wait() sleep() 这些等待效果 跑出一个异常

可以interrupt + 一个中断程序的标志 来结束进程


class Demo implements Runnable
{
    boolean flag=true;
    public synchronized void run()
    {
        while(flag)
        {
            try {
                wait();
            }
            catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + "..." + e);
                //结束标志位
                flag = false;
            }
            //虽然抛出异常 这里还是会执行一次
            System.out.println(Thread.currentThread().getName()+"结束...");
        }
    }
}
public class Main {

    public static void main(String[] args) {
        Demo d=new Demo();
        Thread t1=new Thread(d);
        Thread t2=new Thread(d);
        t1.start();
        t2.start();
        t1.interrupt();
        t2.interrupt();
    }
}

运行结果:


你可能感兴趣的:(我的日志,Java,多线程)