一: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); } } });