So, I checked the test, and the results do not make any sense to me. Consider the following code:
ThreadStuffCounter counter_1 = new ThreadStuffCounter(1); while(counter_1.doProceed) { Thread.sleep(500); Thread thread = new Thread(counter_1); thread.start(); }
With Runnable as follows:
package test; public class ThreadStuffCounter implements Runnable { public volatile boolean doProceed = true; private int id = -1; public volatile int i = -1; public ThreadStuffCounter(int id) { this.id = id; } @Override public void run() { for (i = 0; i < 10; i++) { System.out.println("i = " + i + " in runnable id = " + id); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } doProceed = false; } }
Only one counter instance is shared between threads. It will take less time to start another thread, but even one step that needs to be done in counter.doProceed should, as I understand it, never be set to false, and the loop should go on indefinitely until I get an exception from memory and I can no longer start flows.
How can I get out of a loop?
EDIT: modified code to make sure the answer is below.
package test; public class ThreadStuffCounter implements Runnable{ public volatile boolean doProceed = true; private int id = -1; volatile int i = -1; public ThreadStuffCounter(int id){ this.id = id; } @Override public void run() { i = 0; while (i < 10){ System.out.println("i = " + i + " in runnable id = " + id + "; from thead id = " + Thread.currentThread().getId()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } i++; } ThreadStuff.doProceed = false; }
}
AND
package test; public class ThreadStuff { public static volatile boolean doProceed = true; public static void main (String[] args) throws InterruptedException{ ThreadStuffCounter counter_1 = new ThreadStuffCounter(1); while(doProceed){ Thread.sleep(500); Thread thread = new Thread(counter_1); thread.start(); } }
}
In addition, it appears more than n threads if you are working for i <n. You need a lot, so n threads increase at the same time.
source share