It is impossible to put synchronized on the whole while, since the threads will just be executed one after another and that's it. You need to somehow synchronize inside while, but how?

static int x = 0; static int count = 0; static class LuckyThread extends Thread { @Override public void run() { while (x < 999999) { x++; if ((x % 10) + (x / 10) % 10 + (x / 100) % 10 == (x / 1000) % 10 + (x / 10000) % 10 + (x / 100000) % 10) { System.out.println(x); count++; } } } } 
  • And what exactly do you want to synchronize? - KoVadim

2 answers 2

If I understood correctly, then you start n streams and everyone should count the sum of digits of 6-digit numbers. This is done using the AtomicInteger class AtomicInteger

 static AtomicInteger x = new AtomicInteger(0); static AtomicInteger count = new AtomicInteger(0); static class LuckyThread extends Thread { private int sum(int val) { int res = 0; while (val > 0) { res += val % 10; val /= 10; } return res; } @Override public void run() { int val = x.incrementAndGet(); while (val < 999999) { if (sum(val % 1000) == sum(val / 1000)) { System.out.println(val); count.incrementAndGet(); } val = x.incrementAndGet(); } } } 
  • In the sum() method, the loop condition is better to do val > 0 - and then an extra pass is performed with zero, which does not change anything - m. vokhm
  • @ m.vokhm You are right. Something I was not thinking about. Corrected - Anton Shchyrov

Your task is perfectly parallel, and there is no need to use any synchronization. Right at all.

We divide this range (0 ... 1000000) into N ranges, and each range is calculated in a separate stream. And N is the number of threads.

 public static int parallelSearch(int threadCount) throws Exception { ExecutorService threadPool = Executors.newFixedThreadPool(threadCount); Collection<Future<Integer>> futures = new ArrayList<>(threadCount); int limit = 1_000_000; int step = limit / threadCount; int x = 0; while (x < limit) { int finalX = x; futures.add(threadPool.submit(() -> search(finalX, finalX + step))); x += step; } int result = 0; for (Future<Integer> future : futures) result += future.get(); return result; } private static int search(int x, int limit) { int count = 0; while (x <= limit) { x++; if ((x % 10) + (x / 10) % 10 + (x / 100) % 10 == (x / 1000) % 10 + (x / 10000) % 10 + (x / 100000) % 10) { System.out.println(x); count++; } } return count; }