自旋锁
package algorithm;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock() {
System.out.println(Thread.currentThread().getName() + "\t" + "coming");
while (!atomicReference.compareAndSet(null, Thread.currentThread())) {
}
}
public void unMyLock() {
atomicReference.compareAndSet(Thread.currentThread(), null);
System.out.println(Thread.currentThread().getName() + "\t" + "coming");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(()->{
try {
spinLockDemo.myLock();
Thread.sleep(5000);
spinLockDemo.unMyLock();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"AA").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.myLock();
spinLockDemo.unMyLock();
},"BB").start();
}
}
读写锁
package algorithm;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReentrantReadWriteLockDemo{
public static void main(String[] args) {
WriteAndReadLock writeAndReadLock = new WriteAndReadLock();
for(int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(()->{
writeAndReadLock.put(tempInt + "", tempInt+ "");
},String.valueOf(i)).start();
new Thread(()->{
writeAndReadLock.get(tempInt + "");
},String.valueOf(i)).start();
}
}
}
class WriteAndReadLock{
public volatile Map<String,Object> map = new HashMap<>();
ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
reentrantReadWriteLock.writeLock().lock();
try {
System.out.println("正在写入" + "\t" + key);
map.put(key,value);
System.out.println("写入完成" + "\t" + key);
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
public void get(String key) {
reentrantReadWriteLock.readLock().lock();
try {
System.out.println("正在读取" + "\t" + key);
Object result = map.get(key);
System.out.println("读取完成" + "\t" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantReadWriteLock.readLock().unlock();
}
}
}
门栓
package algorithm;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for(int i = 1 ; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "\t" + "被灭了");
countDownLatch.countDown();
},CountryEnum.FOR_EACH_COUNTRYENUM(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "\t" + "秦国统一华夏");
System.out.println(CountryEnum.ONE);
System.out.println(CountryEnum.ONE.getRetCode());
System.out.println(CountryEnum.ONE.getRetMessage());
}
}
package algorithm;
import lombok.Getter;
public enum CountryEnum {
ONE(1,"齐国"),
TWO(2,"燕国"),
THREE(3,"楚国"),
FOUR(4,"赵国"),
FIVE(5,"魏国"),
SIX(6,"韩国");
@Getter
private Integer retCode;
@Getter
private String retMessage;
CountryEnum(Integer retCode, String retMessage) {
this.retCode = retCode;
this.retMessage = retMessage;
}
public static CountryEnum FOR_EACH_COUNTRYENUM(int index) {
CountryEnum[] values = CountryEnum.values();
for(CountryEnum countryEnum : values) {
Integer retCode = countryEnum.getRetCode();
if(index == retCode) {
return countryEnum;
}
}
return null;
}
}
增加到指定值7后程序结束
package algorithm;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
// CyclicBarrier(int parties, Runnable barrierAction)
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() + "\t" +"第" + tempInt + "颗龙珠被找到");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
信号灯,模拟停车场景
package algorithm;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "\t" + "抢到车位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "\t" + "离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
阻塞队列
package algorithm;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
public class BlockingQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingDeque = new ArrayBlockingQueue<>(3);
// System.out.println(blockingDeque.add("a"));
// System.out.println(blockingDeque.add("b"));
// System.out.println(blockingDeque.add("c"));
// System.out.println(blockingDeque.add("x"));
System.out.println(blockingDeque.offer("a"));
System.out.println(blockingDeque.offer("b"));
// System.out.println(blockingDeque.offer("c"));
// System.out.println(blockingDeque.offer("d"));
System.out.println(blockingDeque.offer("x"));
System.out.println(blockingDeque.peek());
System.out.println(blockingDeque.poll());
System.out.println(blockingDeque.poll());
System.out.println(blockingDeque.poll());
System.out.println(blockingDeque.poll());
SynchronousQueue synchronousQueue = new SynchronousQueue();
}
}
阻塞不存储队列
package algorithm;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class SynchronousQueueDemo {
public static void main(String[] args) {
SynchronousQueue synchronousQueue = new SynchronousQueue();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "\t" + "put a 完成");
synchronousQueue.put("a");
System.out.println(Thread.currentThread().getName() + "\t" + "put b 完成");
synchronousQueue.put("b");
System.out.println(Thread.currentThread().getName() + "\t" + "put c 完成");
synchronousQueue.put("c");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "AAA").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t" + "得到" + synchronousQueue.take());
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t" + "得到" + synchronousQueue.take());
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t" + "得到" + synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "BBB").start();
}
}
传统的生产者消费者模式
package algorithm;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareData {
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void increment() {
lock.lock();
try {
while (number != 0) {
condition.await();
}
number++;
condition.signalAll();
System.out.println(Thread.currentThread().getName() + "\t" + number);
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void decrement() {
lock.lock();
try {
while (number == 0) {
condition.await();
}
number--;
condition.signalAll();
System.out.println(Thread.currentThread().getName() + "\t" + number);
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class ProCounsumer_TraditionDemo {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(()->{
for(int i = 1; i <= 5; i++) {
shareData.increment();
}
},"AAA").start();
new Thread(()->{
for(int i = 1; i <= 5; i++) {
shareData.decrement();
}
},"BBB").start();
}
}
多线程按顺序执行,AA->BB-CC,循环10次
package algorithm;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SynAndReentrantLockDemo {
private int number = 1;
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
private void print5() {
lock.lock();
try {
// 判断
while(number != 1) {
c1.await();
}
// 干活
for(int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
// 通知
number = 2;
c2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private void print10() {
lock.lock();
try {
// 判断
while(number != 2) {
c2.await();
}
// 干活
for(int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
// 通知
number = 3;
c3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private void print15() {
lock.lock();
try {
// 判断
while(number != 3) {
c3.await();
}
// 干活
for(int i = 1; i <= 15; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
// 通知
number = 1;
c1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
SynAndReentrantLockDemo synAndReentrantLockDemo = new SynAndReentrantLockDemo();
new Thread(()->{
for(int i = 1; i < 10; i++) {
synAndReentrantLockDemo.print10();
}
},"BB").start();
new Thread(()->{
for(int i = 1; i < 10; i++) {
synAndReentrantLockDemo.print15();
}
},"CC").start();
new Thread(()->{
for(int i = 1; i < 10; i++) {
synAndReentrantLockDemo.print5();
}
},"AA").start();
}
}
消费者生产者模式
package algorithm;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ProComsumer_BlockQueueDemo {
private volatile boolean FLAG = true;
private AtomicInteger atomicInteger = new AtomicInteger();
private BlockingQueue<String> blockingQueue = null;
public ProComsumer_BlockQueueDemo(BlockingQueue blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
private void myProduct() throws InterruptedException {
String data = null;
while (FLAG) {
data = atomicInteger.getAndIncrement() + "";
boolean offer = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
if (offer) {
System.out.println(Thread.currentThread().getName() + "\t" + "插入队列成功");
} else {
System.out.println(Thread.currentThread().getName() + "\t" + "插入队列失败");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println(Thread.currentThread().getName() + "\t" + "FLAG = false插入停止");
}
private void myConsumer() throws InterruptedException {
while (FLAG) {
String data = blockingQueue.poll(2, TimeUnit.SECONDS);
if (StringUtils.isBlank(data)) {
System.out.println(Thread.currentThread().getName() + "\t" + "超过两秒没有获取蛋糕,消费退出");
FLAG = false;
return;
}
System.out.println(Thread.currentThread().getName() + "\t" + "消费成功");
}
}
private void stop() {
this.FLAG = false;
}
public static void main(String[] args) throws InterruptedException {
ProComsumer_BlockQueueDemo proComsumer_blockQueueDemo = new ProComsumer_BlockQueueDemo(new ArrayBlockingQueue(10));
new Thread(() -> {
try {
proComsumer_blockQueueDemo.myProduct();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "AA").start();
new Thread(() -> {
try {
proComsumer_blockQueueDemo.myConsumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "BB").start();
TimeUnit.SECONDS.sleep(5);
System.out.println("5秒钟到了,程序停止");
proComsumer_blockQueueDemo.stop();
}
}