循环线程打印

几个线程,循环打印1 - 100


    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        new Main().printfTo100();

    }

    public boolean isStop = false;

    public class Model {

        private int count = 0;
        private Model next;

        public void setCount(int count) {
            this.count = count;
        }

        public Model getNext() {
            return next;
        }

        public void setNext(Model model) {
            this.next = model;
        }

        public int getCount() {
            return count;
        }

    }

    private void printfTo100() throws InterruptedException {

        // 创建数据描述
        Model modelA = new Model();
        Model modelB = new Model();
        Model modelC = new Model();

        // 形成一个数据循环
        modelA.setNext(modelB);
        modelB.setNext(modelC);
        modelC.setNext(modelA);

        // 创建线程
        MyThread thradA = new MyThread(modelA);
        MyThread thradB = new MyThread(modelB);
        MyThread thradC = new MyThread(modelC);

        // 启动线程
        thradA.start();
        thradB.start();
        thradC.start();

        Thread.sleep(1000);

        synchronized (modelA) {
            modelA.notify();
        }


    }

    public class MyThread extends Thread {


        private Model model;

        public MyThread(Model model) {
            this.model = model;
        }

        public void run() {
            try {
                // 忽略异常处理
                synchronized (model) {
                    while (!isStop) {
                        // 每个线程创建的时候 先wait
                        model.wait();
                        if (isStop) {
                            break;
                        }
                        // 被唤醒之后,打印对应的数字
                        System.out.println(model.getCount());
                        if (model.getCount() >= 100) {
                            Main.this.stop(model);
                            break;
                        }
                        // 下一个线程,加上1
                        model.getNext().setCount(model.getCount() + 1);
                        // 通知下一个线程开始工作
                        synchronized (model.getNext()) {
                            model.getNext().notify();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public void stop(Model model) {
        isStop = true;
        Model temp = model.next;
        while (temp != model) {
            synchronized (temp) {
                temp.notify();
            }
            temp = temp.next;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值