一个关于多个线程执行同一个操作(插入数据)用锁控制重复插入的实例

时间:2022-09-29 16:21:37

public class ThreadInsert {

public static void main(String[] args) {
final ThreadInsert cuijimanageServiceImpl=new ThreadInsert();
final List<String> strList=new ArrayList<String>();
strList.add("0");
Thread thread1= new Thread(){
@Override
public void run() {
cuijimanageServiceImpl.show(strList);
}
};
Thread thread2= new Thread(){
@Override
public void run() {
cuijimanageServiceImpl.show(strList);
}
};

Thread thread3= new Thread(){
@Override
public void run() {
cuijimanageServiceImpl.show(strList);
}
};
Thread thread4= new Thread(){
@Override
public void run() {
cuijimanageServiceImpl.show(strList);
}
};
Thread thread5= new Thread(){
@Override
public void run() {
cuijimanageServiceImpl.show(strList);
}
};
Thread thread6= new Thread(){
@Override
public void run() {
cuijimanageServiceImpl.show(strList);
}
};

thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();

try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();

} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(strList);

}
public void show( List<String> strList){
int size = strList.size();
if(size<2){
synchronized (this){
if(strList.size()<2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
strList.add("test");
}
}
}
}
public void show1( List<String> strList){
int size = strList.size();
if(size<2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
strList.add("test");
}
}
}