一個關於多個線程執行同一個操作(插入數據)用鎖控制重復插入的實例


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");
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM