多线程学习笔记3之ReentrantLock

比较LongAdder、AtomicLong、synchronized(Long)效率
public class AtomicVsSyncVsLongAdder {
    static long count2 = 0L;
    static AtomicLong count1 = new AtomicLong(0L);
    static LongAdder count3 = new LongAdder();

    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[1000];

        for (int i = 0; i < threads.length; i++) {
            threads[i] =
                    new Thread(() -> {
                        for (int k = 0; k < 100000; k++) count1.incrementAndGet();
                    });
        }

        long start = System.currentTimeMillis();

        for (Thread t : threads) t.start();

        for (Thread t : threads) t.join();

        long end = System.currentTimeMillis();

        //TimeUnit.SECONDS.sleep(10);

        System.out.println("Atomic: " + count1.get() + " time " + (end - start));
        //-----------------------------------------------------------
        Object lock = new Object();

        for (int i = 0; i < threads.length; i++) {
            threads[i] =
                    new Thread(() -> {

                        for (int k = 0; k < 100000; k++)
                            synchronized (lock) {
                                count2++;
                            }
                    });
        }

        start = System.currentTimeMillis();

        for (Thread t : threads) t.start();

        for (Thread t : threads) t.join();

        end = System.currentTimeMillis();


        System.out.println("Sync: " + count2 + " time " + (end - start));


        //----------------------------------
        for (int i = 0; i < threads.length; i++) {
            threads[i] =
                    new Thread(() -> {
                        for (int k = 0; k < 100000; k++) count3.increment();
                    });
        }

        start = System.currentTimeMillis();

        for (Thread t : threads) t.start();

        for (Thread t : threads) t.join();

        end = System.currentTimeMillis();

        //TimeUnit.SECONDS.sleep(10);

        System.out.println("LongAdder: " + count1.longValue() + " time " + (end - start));

    }

    static void microSleep(int m) {
        try {
            TimeUnit.MICROSECONDS.sleep(m);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

这个小程序用了1000个线程,每个线程分别将值从0到100000递增,然后计算所用的时间,结果如下图所示

在这里插入图片描述

可以看到LongAdder效率最高,其次是AtomicLong,synchronize最慢
原因是AtomicLong是CAS(无锁)效率比synchronize高,而LongAdder是使用分段锁,将1000个线程分成5份,200个线程一组去加值,最后将5个加起来的结果再相加,优势是在线程较多的情况下效率比AtomicLong更高

可重入锁 ReentrantLock
  • ReentrantLock是一种可重入锁,跟synchronized作用差不多,但功能比synchronized要多,比如ReentrantLock可以设置等待时间,假如在指定时间内未拿到锁,则会放弃,代码如下
Lock lock = new ReentrantLock();

    void m1() {
        try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);

                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 使用tryLock进行尝试锁定,不管锁定与否,方法都将继续执行
     * 可以根据tryLock的返回值来判定是否锁定
     * 也可以指定tryLock的时间,由于tryLock(time)抛出异常,所以要注意unclock的处理,必须放到finally中
     */
    void m2() {

        boolean locked = false;

        try {
            locked = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2 ..." + locked);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(locked) lock.unlock();
        }

    }

    public static void main(String[] args) {
        ReentrantLockDemo2 rl = new ReentrantLockDemo2();
        new Thread(rl::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(rl::m2).start();
    }

结果:m2 …false,如果将循环次数改为4,则结果为m2 …true

公平锁 非公平锁

ReentrantLock可以在构造的时候进行设置是否为公平锁,公平锁不是绝对公平,而是相对公平,看代码

public class ReentrantLockDemo3 extends Thread {

    //参数为true表示为公平锁,请对比输出结果
    private static ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁");
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo3 rl = new ReentrantLockDemo3();
        Thread th1 = new Thread(rl);
        Thread th2 = new Thread(rl);
        th1.start();
        th2.start();
    }

结果是两个线程基本交替打印

CountDownLatch 门栓
  • 是门栓,可以用在等待线程执行完毕后再进行业务的场景下,代码如下
public class CountDownLatchDemo {

    public static void main(String[] args) {
        usingCountDown();
//        usingJoin();
    }


    private static void usingCountDown() {
        Thread[] threads = new Thread[100];

        CountDownLatch latch = new CountDownLatch(threads.length);

        for (int i = 0; i < threads.length; i++) {
            int finalI = i;
            threads[i] = new Thread(() -> {
                int result = 0;
                for (int j = 0; j < 100; j++) {
                    result += j;
                }
                System.out.println("thread " + finalI + " result = " + result);
                latch.countDown();
            });
        }
        for (Thread thread : threads) {
            thread.start();
        }

        try {
            // 这段代码处于阻塞状态,当100个线程都执行完毕的时候才打印countDown end...
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("countDown end...");
    }

    private static void usingJoin() {
        Thread[] threads = new Thread[100];

        for (int i = 0; i < threads.length; i++) {
            int finalI = i;
            threads[i] = new Thread(() -> {
                int result = 0;
                for (int j = 0; j < 100; j++) {
                    result += j;
                }
                System.out.println("thread " + finalI + " result = " + result);
            });
        }

        for (Thread thread1 : threads) {
            thread1.start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("end join");
    }
}

CyclicBarrier 栅栏
  • 栅栏的作用是等待,等待线程达到一定数量的时候,推到,运行一段逻辑,请看下面的示例
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(20, () -> System.out.println("满人,发车"));

        for (int i = 0; i < 100; i++) {

            new Thread(() -> {
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

执行结果:就是打印5次 满人,发车

读写锁 ReadWriteLock
  • 读锁ReentrantReadWriteLock.WriteLock本质上是一把共享锁
  • 写锁ReentrantReadWriteLock.ReadLock本质上是一把排它锁

看下面一段程序,可以发现假如都是用共享锁,大概需要20秒的时间才能执行完,但是当是用读锁和写锁,则大概只需要3秒钟时间

public class ReadWriteLockDemo {

    private static int value;

    // 定义一个排他锁
    static Lock lock = new ReentrantLock();

    // 定义读写锁
    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 读锁
    static Lock readLock = readWriteLock.readLock();

    // 写锁
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock) {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(1);
            System.out.println("read over...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock, int v) {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(1);
            value = v;
            System.out.println("write over!");
            //模拟写操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        // 排他锁
//        Runnable readR = ()->read(lock);
        // 读锁 共享锁
        Runnable readR = () -> read(readLock);
        // 排他锁
//        Runnable writeR = () -> write(lock, 10);

        // 写锁 排它锁
        Runnable writeR = () -> write(writeLock, 10);

        for(int i=0; i<18; i++) new Thread(readR).start();
        for(int i=0; i<2; i++) new Thread(writeR).start();
    }

}
信号量 Semaphore
  • Semaphore作用是限流,用来限制同时运行的线程数
  • 车道 加油站

简单使用代码

public class SemaphoreDemo {

    public static void main(String[] args) {
        //Semaphore s = new Semaphore(2);
        Semaphore s = new Semaphore(2, true);
        //允许一个线程同时执行
        //Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值