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