ReentrantLock

2017-05-16  本文已影响4人  heiheiwanne

以锁的方式循环执行两个线程,当然也可以使用lock.newCondition实现线程的唤醒

Condition con1 = lock.newCondition();

        final Lock lock = new ReentrantLock();

        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    int i = 0;
                    lock.lock();

                    Log.e("xmq", "aaaaaaaaaa");
                    lock.unlock();
                    try {
                        sleep(1000l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };


        Thread thread1 = new Thread() {
            @Override
            public void run() {

                while (true) {
                    int i = 0;
                    lock.lock();
                    Log.e("xmq", "bbbbbbbbbbbbb");
                    lock.unlock();
                    try {
                        sleep(1000l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

            thread.start();
            thread1.start();

ReentrantReadWriteLock 读写锁

上一篇下一篇

猜你喜欢

热点阅读