栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自旋锁和读写锁代码块

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自旋锁和读写锁代码块

自旋锁
package algorithm;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLockDemo {
    AtomicReference 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 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();
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/877216.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号