自实现的线程自旋锁
读写锁
写锁
读锁
CountDownLatch做加法
CylicBarrierDemo做减法
Semaphore 抢车位
代码
package com.ge.healthcare.cn.apm.gateway.util;
import java.util.concurrent.*;import java.util.concurrent.atomic.AtomicReference;
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"come in");
while (!atomicReference.compareAndSet(null,thread)){}
}
public void myUnlock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName()+" invoked myUnLock()");
}
public static void main(String[] args) {
//自己实现的自旋锁
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(()->{
spinLockDemo.myLock();
System.out.println(Thread.currentThread().getName()+"正在干活");
try{TimeUnit.SECONDS.sleep(10);}catch (InterruptedException e){e.printStackTrace();}
spinLockDemo.myUnlock();
},"AA").start();
try{TimeUnit.SECONDS.sleep(2);}catch (InterruptedException e){e.printStackTrace();}
new Thread(()->{
spinLockDemo.myLock();
System.out.println(Thread.currentThread().getName()+"正在干活");
spinLockDemo.myUnlock();
},"BB").start();
//CountDownLatch
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i <=6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"上完自习离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start(); }
try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"————————最后关门");
//CylicBarrierDemo做减法
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("集齐");
});
for (int i = 1; i <=7 ; i++) {
final int tempInt = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集到第:"+tempInt+"个"); try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
//Semaphore抢车位
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <=6 ; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到");
try{TimeUnit.SECONDS.sleep(3);}catch (InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"离开");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}