Note that there are some explanatory texts on larger screens.

plurals
  1. POJava multi threaded Atomic Integer increment on error
    text
    copied!<p>So I have a little problem. I am checking lots of numbers in a loop, where the number is just an <code>AtomicInteger</code> that is incremented every time. The problem is that sometimes there is an "error" (the error has to do with the server, not program) and the thread needs to sleep. After they sleep, I would like all of the threads to go back and recheck the numbers that they missed because of the error, but it will only recheck the last one, because the <code>AtomicInteger</code> was already incremented. Here is my code: </p> <pre><code>public class Red extends java.lang.Thread { private final LinkedBlockingQueue&lt;Integer&gt; queue; public Red(LinkedBlockingQueue&lt;Integer&gt; 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" ) &gt; -1 || reply.asText().indexOf( "unavailable" ) &gt; -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; } } } } </code></pre> <p>Here is my code for to star the threads:</p> <pre><code>List&lt;LinkedBlockingQueue&lt;Integer&gt;&gt; queuelist = new ArrayList&lt;LinkedBlockingQueue&lt;Integer&gt;&gt;(); for (int n = 0; n &lt; threads; n++) { queuelist.add(new LinkedBlockingQueue&lt;Integer&gt;()); java.lang.Thread t = new Red(queuelist.get(n)); t.start(); } java.lang.Thread a = new MainThread(queuelist); a.start(); </code></pre> <p>Here is my code for MainThread:</p> <pre><code>public class MainThread extends java.lang.Thread { final private List&lt;LinkedBlockingQueue&lt;Integer&gt;&gt; queues; final private AtomicInteger atomicInteger = new AtomicInteger(10000000); public MainThread(List&lt;LinkedBlockingQueue&lt;Integer&gt;&gt; queues) { this.queues = queues; } public void run() { while (true) { int temp = atomicInteger.getAndIncrement(); for(LinkedBlockingQueue&lt;Integer&gt; queue : queues) { queue.offer(temp); } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload