Java多執行緒場景模擬(1)
阿新 • • 發佈:2019-01-02
1.業務場景簡介
儲存使用者個人設定,一個使用者在a表中只能存在一條記錄,使用者修改記錄時,檢查如果該記錄存在,則修改該資料,如果該記錄不存在,則插入一條記錄。
2. 問題說明
多執行緒情況下,會出現一個使用者在表中有多條記錄存在的情況。
3. 原因解釋
比如說併發兩個執行緒A和執行緒B, 執行緒A檢查記錄不存在,準備插入記錄,這時CPU切換到執行緒B,這是執行緒B檢查記錄仍是不存在,執行緒B插入一條資料,執行緒B結束。然後CPU切換到執行緒A,A繼續插入記錄,這是資料庫就會有兩條記錄。
package com.salen.test; import java.util.concurrent.atomic.AtomicInteger; public class MultiThreadTest { //計數器,記錄插入次數 static AtomicInteger num = new AtomicInteger(0); //記錄是否存在, 模擬資料庫記錄,表示某條資訊是否存在 static boolean exist = false; public static void main(String[] args) { //起20個執行緒,同時執行檢查插入操作 for (int i = 0; i < 20; i++) { new Thread(new Runnable() { @Override public void run() { try { MultiThreadTest test = new MultiThreadTest(); test.generate(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } /** * 模擬修改一條資料 * 先去檢查該資料是否存在, * 如果該記錄存在,則修改該資料,如果資料不存在,則插入一條新的資料 * @throws InterruptedException */ private void generate() throws InterruptedException{ if(exist){ Thread.sleep(1000); // 處理業務 100毫秒 System.out.println("record has exist..., update it "); }else{ Thread.sleep(100); // 處理業務 100毫秒 System.out.println("record not exist..., insert into it, time = " + num.incrementAndGet()); exist = true; } } }
測試結果
record not exist..., insert into it, time = 2 record not exist..., insert into it, time = 3 record not exist..., insert into it, time = 1 record not exist..., insert into it, time = 4 record not exist..., insert into it, time = 5 record not exist..., insert into it, time = 6 record not exist..., insert into it, time = 7 record not exist..., insert into it, time = 8 record not exist..., insert into it, time = 10 record not exist..., insert into it, time = 9 record not exist..., insert into it, time = 11 record not exist..., insert into it, time = 12 record not exist..., insert into it, time = 13 record not exist..., insert into it, time = 14 record not exist..., insert into it, time = 15 record not exist..., insert into it, time = 17 record not exist..., insert into it, time = 16 record not exist..., insert into it, time = 18 record not exist..., insert into it, time = 19 record not exist..., insert into it, time = 20