一、问题阐述
在日常项目中可能存在需要防止用户数据并发操作的问题,需要对代码块加锁保护。例如:用户输入存数据库,重复数据不存DB;用户操作缓存数据等,这里想尽可能把锁的对象放小,因此通常都是锁用户而不是锁整个类或者代码块;然而在用synchronized(userId)的时候可能会存在一些问题。
二、synchronized 锁字符串的问题
使用synchronized 锁字符串存在的问题,下面示例锁一个字符串。
public class ThreadTest implements Runnable{
@Override
public void run(){
String threadName = Thread.currentThread().getName();
synchronized (threadName) {
//线程进入
System.out.println(threadName + " thread start");
try {
//进入后睡眠
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//线程结束
System.out.println(threadName + " thread end");
}
}
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
Thread thread =