Java多线程Atomic Integer在出错时递增

时间:2013-06-03 01:16:43

标签: java atomic

所以我有一点问题。我在循环中检查大量数字,其中数字只是AtomicInteger,每次都会增加。问题是有时会出现错误" (错误与服务器有关,而不是程序),线程需要休眠。在他们睡觉之后,我希望所有的线程都返回并重新检查他们因错误而错过的数字,但它只会重新检查最后一个,因为AtomicInteger已经增加了。这是我的代码:

public class Red extends java.lang.Thread {
        private final LinkedBlockingQueue<Integer> queue;

    public Red(LinkedBlockingQueue<Integer> queue) {
        this.queue = queue;
    }

        public void run()
    {
while(true){
    try{
int i = queue.take();
Main.code.setValueAttribute(""+i);
HtmlPage reply = (HtmlPage)Main.btnFinal.click();
Main.webClient.waitForBackgroundJavaScript(Main.r.nextInt(500));
if ( reply.asText().indexOf( "Error" ) > -1 || reply.asText().indexOf( "unavailable" ) > -1) {
int sleep = Main.r.nextInt(900000);
System.out.println(" error, on "+i+" sleeping for "+ sleep);
Thread.sleep(sleep);
continue;
}
System.out.println("Code "+i+" checked.");
    }catch(Exception e){
        e.printStackTrace();
        continue;
    }
}

        }
}

这是我的主题代码:

List<LinkedBlockingQueue<Integer>> queuelist = new ArrayList<LinkedBlockingQueue<Integer>>();
   for (int n = 0; n < threads; n++) {
    queuelist.add(new LinkedBlockingQueue<Integer>());
    java.lang.Thread t = new Red(queuelist.get(n));
    t.start();
   }
java.lang.Thread a = new MainThread(queuelist);
a.start();

这是我的MainThread代码:

public class MainThread extends java.lang.Thread {
    final private List<LinkedBlockingQueue<Integer>> queues;
    final private AtomicInteger atomicInteger = new AtomicInteger(10000000);

    public MainThread(List<LinkedBlockingQueue<Integer>> queues) {
        this.queues = queues;
    }

    public void run() {
        while (true) {
            int temp = atomicInteger.getAndIncrement();
            for(LinkedBlockingQueue<Integer> queue : queues) {
                queue.offer(temp);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果我理解了这个问题,那么一个解决方案是给每个线程自己的BlockingQueue<Integer>ConcurrentLinkedQueue<Integer>;然后,主线程的循环将AtomicIntegeroffer的值递增到每个队列,并且线程将在其队列中takepoll来检索整数和处理它们。这样,如果线程休眠,它将不会遗漏任何整数 - 它们在唤醒时会在队列中等待它。

public class MainThread extends java.lang.Thread {
    final private List<BlockingQueue<Integer>> queues;
    final private AtomicInteger atomicInteger = new AtomicInteger();

    public MainThread(List<BlockingQueue<Integer>> queues) {
        this.queues = queues;
    }

    public void run() {
        while (true) {
            int temp = atomicInteger.getAndIncrement();
            for(BlockingQueue<Integer> queue : queues) {
                queue.offer(temp);
            }
        }
    }
}

public class WorkerThread extends java.lang.Thread {
    private final BlockingQueue<Integer> queue;

    public WorkerThread(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    public void run() {
        while(true) {
            int temp = queue.take();
            // process temp
        }
    }
}