美文网首页
synchronized--交替打印

synchronized--交替打印

作者: 大蓝鲸_7bfa | 来源:发表于2018-06-28 16:37 被阅读0次

    public class TwoThreadSynchronized {

    private int    start =1;

        private boolean flag  =false;

        public static void main(String[] args) {

    TwoThreadSynchronized twoThreadWaitNotify =new TwoThreadSynchronized();

            Thread t1 =new Thread(new OuNum(twoThreadWaitNotify));

            t1.setName("t1");

            Thread t2 =new Thread(new JiNum(twoThreadWaitNotify));

            t2.setName("t2");

            t1.start();

            t2.start();

        }

    public static class OuNumimplements Runnable {

    TwoThreadSynchronizednumber;

            public OuNum(TwoThreadSynchronized twoThreadWaitNotify) {

    this.number = twoThreadWaitNotify;

            }

    @Override

            public void run() {

    while (number.start <=100) {

    synchronized (TwoThreadSynchronized.class) {

    System.out.println("偶数抢到锁了");

                        if (number.flag) {

    System.out.println("number:" +number.start);

                            number.start++;

                            number.flag =true;

                            TwoThreadSynchronized.class.notify();

                        }else {

    try {

    TwoThreadSynchronized.class.wait();

                            }catch (InterruptedException e) {

    e.printStackTrace();

                            }

    }

    }

    }

    }

    }

    public static class JiNumimplements Runnable {

    TwoThreadSynchronizednumber;

            public JiNum(TwoThreadSynchronized number) {

    this.number = number;

            }

    @Override

            public void run() {

    while (number.start <=100) {

    synchronized (TwoThreadSynchronized.class) {

    System.out.println("奇数抢到了");

                        if (!number.flag) {

    System.out.println("number:" +number.start);

                            number.start++;

                            number.flag =true;

                            TwoThreadSynchronized.class.notify();

                        }else {

    try {

    TwoThreadSynchronized.class.wait();

                            }catch (InterruptedException e) {

    e.printStackTrace();

                            }

    }

    }

    }

    }

    }

    相关文章

      网友评论

          本文标题:synchronized--交替打印

          本文链接:https://www.haomeiwen.com/subject/xxxnyftx.html