多個線程類比多人同時插入操作,多個線程類比插入
1 import java.util.concurrent.ConcurrentLinkedQueue; 2 3 public class BeanOne extends Thread { 4 5 public static ConcurrentLinkedQueue<String> list = new ConcurrentLinkedQueue<String>();// 定義公用的list 6 // 此處使用ConcurrentLinkedQueue為安全執行緒隊列 7 8 public void run() { 9 while (true) {10 String str = list.poll();// 每次彈出一個元素遵循先入先出的原則11 System.out.println(str);12 13 }14 }15 16 }
1 public class ThreadA extends Thread { 2 private String str; 3 4 public ThreadA(String str) { 5 this.str = str; 6 } 7 8 public void run() { 9 int i = 1;10 while (true) { // 類比插入操作,此處為死迴圈每開啟一個線程則認為一個人在做插入操作11 try {12 BeanOne.list.add(str + i);// 寫入ConcurrentLinkedQueue(安全執行緒的隊列可以支援多線程)13 } catch (Exception e) {14 e.printStackTrace();15 }16 i++;17 }18 }19 20 }
1 public class Main { 2 3 public static void main(String[] args) { 4 5 // TODO Auto-generated method stub 6 for (int i = 0; i < 3; i++)// 開啟多線程類比多人同時操作 7 { 8 ThreadA threadA = new ThreadA(null); 9 if (i == 0) {10 threadA = new ThreadA("ThreadA");11 }12 if (i == 1) {13 threadA = new ThreadA("ThreadB");14 }15 if (i == 2) {16 threadA = new ThreadA("ThreadC");17 }18 threadA.start();19 20 }21 BeanOne threadB = new BeanOne();// 啟動輸出線程22 threadB.start();23 24 }25 26 }
首先呢,問題是這樣的:
遇到了一種情況,伺服器比較小,壓力有點大,同時呢又有很多人進行大量的訂單操作,
這個時候,就會出現,漏掉一部分人的請求,顯示的是逾時。
於是,就先將一定時間內的提交人的訂單存起來,然後迴圈遍曆這個集合,進行多線程插入,
這樣應該就不會漏掉一部分了,當然這種方法肯定有弊端,歡迎給為指點。
http://www.xiaosen.win
感謝http://zhidao.baidu.com/business/profile?id=10287的解法