[Multi-threaded high concurrency] 3. Multi-threaded synchronized+ReentrantLock+CountDownLatch+CyclicBarrier+MarriagePhaser+Semaphore and other locks [draft]

join() method: equivalent to adding t1 to the current thread, and waiting for t1 to execute before starting t2.

Yield() method: yield can be called directly with the Thread class. Yield gives up CPU execution rights to threads of the same level and enters the ready state . If no threads of the same level are waiting for the execution rights of the CPU, the thread continues to execute.

wait() method: It can only be used in the Critical Section (synchronized method or synchronized code block) modified by synchronized. When the thread executes this method, the thread loses the lock and enters a blocked state .

sleep() and sleep(time) methods: called by the current thread. When called, the thread sleeps but does not lose the execution opportunity of the lock and CPU, and enters the "WAITING" or "TIMEED_WAITING" state.

notify() method: remind a thread in the "BLOCKED" state to contend for the lock.

notifyAll() method: remind all threads in the "BLOCKED" state to compete for locks.

LockSupport.park() method:

LockSupport.parkNanos() method:

LockSupport.parkUntil() method:

LockSupport.unpark() method:

CountDownLatch:

  • The countDown() method is used to decrement the counter by one, which is generally called by the thread that performs the task.
  • The await() method makes the thread calling the method in a waiting state, which is generally called by the main thread


CyclicBarrier barrier = new CyclicBarrier(20);

 

The syn lock locks the object, and actually locks the two bit bytes in the 64bit of the object header, as well as the lock upgrade. Or the lock is the class, the object of a lock and the class of the lock are
three comparisons: (T02_AtomicVsSyncVsLongAdder)

static long count2 = 0L;用synchronized
static AtomicLong count1 = new AtomicLong(0L);// 因为用了无锁操作
static LongAdder count3 = new LongAdder(); increment()方法 (这里用的分段锁) 各个数组的和为结果。也是CAS操作

 

1、synchronized:

代码见:JUC_T01_ReentrantLock1

特点:

  • 独占锁,易于操作,但是不够灵活。
  • 可重入,自动加锁和解锁。
  • Unable to respond to interrupts.



2、ReentrantLock:不可重入锁

特点:

  • Exclusive lock, unlocking and unlocking need to be done manually
  • Reentrant, but must be unlocked after locking.
  • Can respond to interruption: lock.lockInterruptibly();
  • Fair lock can be realized (that is, the thread that has the longest waiting time on the lock will obtain the right to use the lock. The popular understanding is that whoever has the longest queue time will execute the lock first.)
 



尝试锁ReentrantLock

代码见:JUC_T03_ReentrantLock3
如果没有拿到就会去执行别的线程,如果拿到了就等待执行完了再去执行别的线程。
Lock lock = new ReentrantLock();
locked = lock.tryLock(5, TimeUnit.SECONDS);
if(locked) lock.unlock();

可以被打断的锁ReentrantLock

代码见:JUC_T04_ReentrantLock4
Lock lock = new ReentrantLock();
lock.lockInterruptibly(); //可以对interrupt()方法做出响应
lock.unlock();
t2.interrupt(); //打断线程2的等待

公平锁ReentrantLock

代码见:JUC_T04_ReentrantLock5
private static ReentrantLock lock=new ReentrantLock(true); //默认是false,非公平锁 参数为true表示为公平锁(队列),请对比输出结果,默认为非公平锁.先去看队列里面有没有线程,没有直接执行,有的话先执行队列的线程。 lock.lock(); lock.unlock();


CountDownLatch:

Thread[] threads = new Thread[100];
CountDownLatch latch = new CountDownLatch(threads.length);
latch.countDown();
latch.await();

CyclicBarrier: Wait until it expires and execute it.

// The 20 here specifies how many threads to wait for await to start execution.
CyclicBarrier barrier = new CyclicBarrier(20);
 // Wait, the
 vehicle will depart after the specified data is full barrier.await();
 CyclicBarrier barrier = new CyclicBarrier(20, new Runnable() {             @Override             public void run() {                 System .out.println("Full people, departure");             }         }); The above is equal to: CyclicBarrier barrier = new CyclicBarrier(20, () -> System.out.println("Full people")); Application scenario: complex operation , 1, database 2, network 3, file Concurrent execution: different threads perform different operations.









ReadWriteLock read-write lock : T10_TestReadWriteLock

ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
// 单独拿到读锁
    static Lock readLock = readWriteLock.readLock();
// 单独拿到写锁
static Lock writeLock = readWriteLock.writeLock();
readWriteLock.lock();
readWriteLock.unlock();

Extension:
MarriagePhaser:     Segmented lock. T09_TestPhaser2    

MarriagePhaser phaser = new MarriagePhaser();
// Specify how many times
phaser.bulkRegister(7);
phaser.arriveAndAwaitAdvance();
phaser.arriveAndDeregister(); // End the thread. Unregistered -1
phaser.register();//Add the current thread to +1
and rewrite boolean onAdvance(int phase, int registe

Semaphore: current limit

//Semaphore s = new Semaphore(2);
// Write a few to show that several can be executed at the same time . true is a fair lock, false is an unfair lock
Semaphore s = new Semaphore(1, true);
// -1. Acquire a lock from Semaphore
s.acquire(); // Acquire a lock
from Semaphore // +1 Release a lock from Semaphore
s.release();

Exchanger: Exchange between two threads. Exchange equipment in the game? ?

// Only two threads can exchange
static Exchanger<String> exchanger = new Exchanger<>();
s = exchanger.exchange(s);

LockSupport: Stop thread, no lock required

// The current thread is blocked.
LockSupport.park();
// Continue to run
LockSupport.unpark(t);

 

 

 

 

Guess you like

Origin blog.csdn.net/zw764987243/article/details/109764940