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的解法