Java Concurrent Programming 第一篇

一:java中的锁

1:创建非公平锁
ReentrantLock lock = new ReentrantLock(false);//new ReentrantLock();默认也是false; 参数为true的话,为公平锁
try {
    //加锁
    lock.lock();
    //模拟业务处理用时
    TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
    e.printStackTrace();
} finally {
    //释放锁
    lock.unlock();
}

2:可重入锁

synchronized void setA() throws Exception{
    //进行A操作
    setB();
}

synchronized void setB() throws Exception{
    //进行B操作
    Thread.sleep(1000);
}

3:ReentrantReadWriteLock

public class Test {
    public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public static void main(String[] args) throws Exception {
        //同时写
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new Runnable() {
            public void run() {
                readFile(Thread.currentThread());
            }
        });
        service.execute(new Runnable() {
            public void run() {
                writeFile(Thread.currentThread());
            }
        });
    }
    //读操作
    public static void readFile(Thread thread) {
        lock.readLock().lock();
        boolean readLock = lock.isWriteLocked();
        if (!readLock) {
            System.out.println("当前为读锁!");
        }
        try {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(thread.getName() + ":正在进行读操作……");
            }
            System.out.println(thread.getName() + ":读操作完毕!");
        } finally {
            System.out.println("释放读锁!");
            lock.readLock().unlock();
        }
    }

    // 写操作
    public static void writeFile(Thread thread) {
        lock.writeLock().lock();
        boolean writeLock = lock.isWriteLocked();
        if (writeLock) {
            System.out.println("当前为写锁!");
        }
        try {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(thread.getName() + ":正在进行写操作……");
            }
            System.out.println(thread.getName() + ":写操作完毕!");
        } finally {
            System.out.println("释放写锁!");
            lock.writeLock().unlock();
        }
    }
}

4:自旋锁

private AtomicLong sign =new AtomicLong(0);

public void lock(){
    while(!sign.compareAndSet(0, 2)){
        
    }
}
public void unlock (){
    Thread current = Thread.currentThread();
    sign.compareAndSet(2, 0);
}

5:补充Dateformat改造

     private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
     
     private static ThreadLocal threadLocal = new ThreadLocal();
     
     public static DateFormat getDateFormat() {
            DateFormat df = (DateFormat) threadLocal.get();
            if (df == null) {
                df = new SimpleDateFormat(DATE_FORMAT);  
                threadLocal.set(df);
            }
            return df;
        }

 

6: thread里的多线程里打印日志

Map<String, String> context = MDC.getCopyOfContextMap(); Thread t0 = new Thread(() -> { MDC.setContextMap(context); try { logger.info("ApplicationAntiFraudParser thread0 start!"); long startTime0 = System.currentTimeMillis(); fruadPhoneNumberOrCnid(applicationModel, applicationResultCassModel); logger.info("loanId:{} call fruadPhoneNumberOrCnid cost:{}ms", loanId, System.currentTimeMillis() - startTime0); }catch (Exception e) { logger.error("ApplicationAntiFraudParser thread0 exception", e); }finally { cdl.countDown(); try { MDC.clear(); }catch (Exception e) { LOG.warn("mdc clear exception.", e); } } });

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值