多個線程類比多人同時插入操作,多個線程類比插入

來源:互聯網
上載者:User

多個線程類比多人同時插入操作,多個線程類比插入

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.