Multithreading high concurrency lock segment + 3-atomic synchronization lock

LongAdder

Juc.atomic the package, in the case where complicated high efficiency higher efficiency than AtomicLong

Principle: In the bottom lock is a segmented design, the array is divided into a thread, the threads are locked in the different elements, the calculation result added together. Segmented lock is CAS.

Comparison Efficiency:
Sync <Atomic, without optimistic locking lock (sync necessarily small a small number of concurrent low efficiency, lock escalation)
Atomic <LongAdder, lock segment

ReetrantLock (bottom for CAS)

Reentrant lock: In the same thread, can be repeated to obtain a lock
(sync must be reentrant, if not re-entrant, the subclass can not call the parent class lock)

Lock unlock

Lock lock = new ReetrantLock();
lock.lock();//加锁
lock.unlock();//解锁(finally)

Attempt to obtain a lock

//5秒钟之内获得锁,未获得取消操作
//返回boo值,如果获取到锁返回true
boolean boo = lock.tryLock(5,TimeUnit.SECONDS);

Interruptible lock

lock.lockInterruptibly();//可以对interrupt进行响应

Fair locks

Lock lock = new ReetrantLock(true);//设置为公平锁

CountDownLatch

Reciprocal latch

CountDownLatch cdl = new CountDownLatch(100);//计数100次
cdl.countDown();//在线程执行完毕后,进行倒数计数-1
cdl.await();//等待,在执行完100次后归零,打开门闩

CyclicBarrier

Loop fence (limiting)

1, a complicated operation:
1. database
2. Network
3. File

2, concurrent execution

CyclicBarrier cb = new CyclicBarrier(20,() -> System.out.println("20已满,发车!") );
cb.await();//等待

Phaser

Stage, fencing group. You can control the number of fence, and the fence waiting for the number of threads waiting

static class MyPhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {

            switch (phase) {
                case 0:
                    System.out.println("第一个方法执行!" + registeredParties);
                    System.out.println();
                    return false;
                case 1:
                    System.out.println("第二个方法执行!" + registeredParties);
                    System.out.println();
                    return false;
                case 2:
                    System.out.println("第三个方法执行!" + registeredParties);
                    System.out.println();
                    return false;
                case 3:
                    System.out.println("第四个方法执行!" + registeredParties);
                    return true;//返回true所有线程结束
                default:
                    return true;
            }
        }
    }
     public static void main(String[] args) {

        phaser.bulkRegister(7);//设置栅栏线程个数

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

            new Thread(new Person("p" + i)).start();
        }

        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();

    }
    static class Person implements Runnable {
        String name;

        public Person(String name) {
            this.name = name;
        }

        public void arrive() {
          	System.out.printf(“第一个”);
            phaser.arriveAndAwaitAdvance();//到达等待
        }

        public void eat() {
           System.out.printf(“第二个”);
            phaser.arriveAndAwaitAdvance();
        }

        public void leave() {
           System.out.printf(“第三个”);
           phaser.arriveAndAwaitAdvance();
        }

        private void hug() {
            if(name.equals("1") || name.equals("2")) {
                System.out.printf(“第四个”);
                phaser.arriveAndAwaitAdvance();
            } else {
                phaser.arriveAndDeregister();//到达并取消注册
                //phaser.register()
            }
        }

        @Override
        public void run() {
        	//按序执行
            arrive();


            eat();


            leave();


            hug();

        }
    }

Execution order of the fence, phaser.arriveAndAwaitAdvance (); barrier wait

ReadWriteLock

Write lock
read locks: shared locks
to write locks: exclusive locks (mutex)

ReadWriteLock rwl = new ReentrantReadWriteLock();
Lock readL = rwl.readLock();
Lock writeL = rwl.writeLock();

By reading a shared lock, exclusive write locks, read must be locked to prevent the write operation into the

Semaphore

Semaphore (limiting, ticket)

//允许一个线程同时执行,第二个参数可传true,公平锁属性
Semaphore s = new Semaphore(1);
s.acquire();//如果信号量不为0,取得信号量锁,该信号量由1变为0
s.release();//释放信号量,该信号量由0恢复为1

Exchanger

Two threads to exchange data.
Exchanger container will save the data, when the first thread calls exchange, the thread is blocked, the value placed in the container. The second thread calls exchange, the value placed in the container. After the exchange of two values. Continue with other threads

Exchanger<String> ex = new Exchanger<>();
String result = ex.exchange(result);//两个线程进行调用,互换数据

LockSupport

LockSupport.park();//线程阻塞
LockSupport.unpark();//线程继续执行,unpack可以在park之前调用
Published 25 original articles · won praise 0 · Views 584

Guess you like

Origin blog.csdn.net/RaymondCoder/article/details/105070879