美文网首页
LOCK--交替打印奇偶数

LOCK--交替打印奇偶数

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

    两个线程交替打印奇偶数

    public class TwoThreadLock {

    static Locklock  =new ReentrantLock();

        private int    start =1;

        private boolean flag;

        public static void main(String[] args) {

    TwoThreadLock twoThreadWaitNotifyLock =new TwoThreadLock();

            Thread thread =new Thread(new OuNum(twoThreadWaitNotifyLock));

            thread.setName("t1");

            Thread thread1 =new Thread(new JiNum(twoThreadWaitNotifyLock));

            thread1.setName("t2");

            thread.start();

            thread1.start();

        }

    public static class OuNumimplements Runnable {

    TwoThreadLocknumber;

            public OuNum(TwoThreadLock n1) {

    this.number = n1;

            }

    @Override

            public void run() {

    while (number.start <=100) {

    if (number.flag) {

    try {

    lock.lock();

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

                            number.start++;

                            number.flag =false;

                        }finally {

    lock.unlock();

                        }

    }

    }

    }

    }

    public static class JiNumimplements Runnable {

    TwoThreadLocknumber;

            public JiNum(TwoThreadLock n2) {

    this.number = n2;

            }

    @Override

            public void run() {

    while (number.start <=100) {

    if (!number.flag) {

    try {

    lock.lock();

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

                            number.start++;

                            number.flag =true;

                        }finally {

    lock.unlock();

                        }

    }

    }

    }

    }

    相关文章

      网友评论

          本文标题:LOCK--交替打印奇偶数

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