Java多线程之中断线程、中断状态以及间隔输出

停止线程

停止线程:只要线程停了就叫做停止线程

使用boolean标记方法中断线程:
        class StopRunnable implements Runnable{
            public boolean isOver = false;
            @Override
            public void run() {
                // 利用死循环方式 测试能不能停止线程
                while (!isOver) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            }   
        }
        public class Demo01 {
            public static void main(String[] args) throws InterruptedException {
                StopRunnable sr = new StopRunnable();
                Thread t1 = new Thread(sr);
                t1.start();
                // 给t1线程有执行的时间
                Thread.sleep(3000);
                // 利用标记停止线程
                sr.isOver = true;
                System.out.println("停止线程");
                Thread.sleep(1000);
                System.out.println("主线程结束");
            }
        }
测试interrupt中断线程:
public class Demo {
    public static void main(String[] args) throws InterruptedException {
        StopRunnable sr = new StopRunnable();
        Thread t1 = new Thread(sr);
        t1.start();
        // 给t1线程有执行的时间
        Thread.sleep(3000);
        t1.interrupt();
        System.out.println("停止线程");
        Thread.sleep(1000);
        System.out.println("主线程结束");
    }
}

class StopRunnable implements Runnable{

    @Override
    public void run() {
        // 利用死循环方式 测试能不能停止线程
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 休眠一秒钟(写个死循环 让循环执行一秒结束)
//          long time = System.currentTimeMillis();
//          while (System.currentTimeMillis() - time < 1000) {}
            System.out.println(Thread.currentThread().getName());
        }
    }   
}

测试结果:
实际上interrupt()这个方法设置了isInterrupted布尔值,如果不测试线程是否中断,子线程不会中断
如果线程中有wait()等待或者sleep()休眠
这时调用interrupt方法会抛出一个异常InterruptedException并且清除中断状态,子程序继续运行;
如果线程中没有等待或者休眠
这时调用interrupt方法会设置中断状态(也就是true/false的改变)

测试中断状态

public class Demo {
    public static void main(String[] args) {
        InterruptThread t1 = new InterruptThread();
        InterruptThread t2 = new InterruptThread();
        t1.start();
        t2.start();

        for (int i = 0; i < 50; i++) {
            if (i == 25) {
                t1.isOver = true;
                break;
            }
            System.out.println(i + "----");
        }
        System.out.println("主线程结束");
    }
}

class InterruptThread extends Thread{

    public boolean isOver = false;

    @Override
    public synchronized void run() {
        while (!isOver) {
            try {
                wait(); //放弃CPU执行资源
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "run");
        }
    }   
}
测试结果:线程1进来带着锁遇到wait方法放弃了CPU的执行资源,但是锁会还回去
紧接着线程2拿着锁进来,又遇到wait方法,也放弃了CPU的执行资源,相当于两个线程进入冷冻(中断)状态

注意:如果在非同步方法里调用wait方法,会出现IllegalMonitorStateException异常(对象监视器就是对象锁)
所以在调用wait方法必须拥有对象锁
public class Demo {
    public static void main(String[] args) {
        InterruptThread t1 = new InterruptThread();
        InterruptThread t2 = new InterruptThread();
        t1.start();
        t2.start();

        for (int i = 0; i < 50; i++) {
            if (i == 25) {
                // 调用中断方法来清楚状态
                t1.interrupt();
                t2.interrupt();
                break;
            }
            System.out.println(i + "----");
        }
        System.out.println("主线程结束");
    }
}

class InterruptThread extends Thread{


    @Override
    public synchronized void run() {
        while (true) {
            try {
                wait(); //放弃CPU执行资源
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "run");
        }
    }   
}
测试结果:
调用interrupt方法可以消除该状态,但是碰到wait方法会抛出异常,所以建议进来不要使用interrupt方法
如果要停止线程直接使用标记法来停止,只有遇到了等待状态时,可以使用该方法强行清除该等待状态

间隔输出

需求:
    Person类 姓名 性别
    开启两个线程
    一个对Person对象进行赋值
    一个对Person对象进行打印
    一次打印 张三 男
    一次打印 zahngsan nv
    间隔输出

分析:
    1.先保证要操作都是同一个对象
    2.要保证数据安全需要使用锁并且要使用同一把锁
    3.保证操作的逻辑顺序要对(先赋值 再打印)用 wait 和 notify
    // Person类
    class Person {
        public String name;
        public String gender;
        // 声明标记来切换打印和赋值
        public boolean flag = false;
    }

    // 赋值线程
    class SetRunnable implements Runnable{
        // 利用成员变量 操作同一个对象
        private Person p;

        // 定义一个标识  通过改变标识 来进行间隔赋值
        private boolean isTrue = true;
        // 进行赋值
        public SetRunnable() {
            super();
        }
        public SetRunnable(Person p) {
            super();
            this.p = p;
        }

        @Override
        public void run() {
            while (true) {
                // 多个线程操作共享数据 为了保证两个锁对象相同 使用传进来的对象p
                synchronized (p) {
                    // 先不进入等待 要先进行赋值
                    if (p.flag == true) {
                        // 进行等待
                        try {
                            p.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 间隔赋值
                    if (isTrue) {
                        p.name = "张三";
                        p.gender = "男";
                    } else {
                        p.name = "zhangsan";
                        p.gender = "nv";
                    }
                    // 改变标识符
                    isTrue = !isTrue;
                    // 修改标记
                    p.flag = true;
                    // 唤醒线程
                    p.notify();
                }
            }
        }
    }

    // 打印线程   
    class PrintRunnable implements Runnable{
        private Person p;

        public PrintRunnable() {
            super();
        }

        public PrintRunnable(Person p) {
            super();
            this.p = p;
        }

        @Override
        public void run() {
            while(true) {
                synchronized (p) {
                    if (p.flag == false) {
                        // 进入等待
                        try {
                            p.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(p.name + "---" + p.gender);
                    // 修改标记
                    p.flag = false;
                    // 唤醒线程
                    p.notify();
                }
            }
        }
    }

    public class Demo06 {
        public static void main(String[] args) {
            // 创建对象 使用同一个对象
            Person person = new Person();
            SetRunnable sr = new SetRunnable(person);
            Thread t1 = new Thread(sr);
            t1.start();
            PrintRunnable pr = new PrintRunnable(person);
            Thread t2 = new Thread(pr);
            t2.start();
        }
    }

间隔输出逻辑:
    赋值线程需要赋值完毕,打印线程才能去打印
    打印线程需要打印完毕,赋值线程才能去赋值
    赋值的时候打印线程在等待,等赋值完成后才能去打印打印完成后通知赋值线程继续赋值
实现间隔输出:
    使用一个标记完成切换wait() 和 notify(),实现上面的逻辑
    两个线程必须保证使用同一个标记,所以标记要声明在Person类中
代码优化:把之前上锁的代码封装到类中,从同步代码块封装成同步方法

修改部分代码如下(未改同上):
    class Person {
        // 把操作共享数据的部分写成一个同步方法
        public synchronized void setPerson(String name, String gender) {
            // 等待
            if (flag == true) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.name = name;
            this.gender = gender;
            // 更改标记
            flag = true;
            // 唤醒线程
            this.notify();
        }

        // 打印方法
        public synchronized void printPerson() {

            if (flag == false) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(name + "---" + gender);
            flag = false;
            this.notify();
        }   
    }

    class PrintRunnable implements Runnable{
        @Override
        public void run() {
            while(true) {
                p.printPerson();
            }
        }
    }

    class SetRunnable implements Runnable{
        @Override
        public void run() {
            while (true) {
                if (isTrue) {
                    p.setPerson("张三", "男");
                } else {
                    p.setPerson("zhangsan", "nv");
                }
                // 更改间隔标记
                isTrue = !isTrue;
            }
        }   
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值