1

Ставить synchronized на весь while нельзя,так как потоки просто друг за другом выполнятся и все. Нужно каким-то образом синхронизировать внутри while, но как?

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++;
            }
        }
    }
}
1
  • А что именно хочется синхронизировать?
    – KoVadim
    14 дек 2016 в 16:12

2 ответа 2

1

Если я правильно понял, то Вы запускаете n потоков и каждый должен считать сумму цифр 6-значных чисел. Делается это при помощи класса 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();
    }
  }
}
2
  • В методе sum() условие цикла лучше сделать val > 0 - а то с нулем выполняется лишний проход, который ничего не меняет
    – m. vokhm
    14 дек 2016 в 17:09
  • @m.vokhm Вы правы. Что-то я не о том думал. Поправил 15 дек 2016 в 13:26
1

У вас задача прекрасно параллелится, и тут не нужно использовать никакую синхронизацию. Прямо совсем.

Разбиваем данный диапазон (0 ... 1000000) на N диапазонов, и каждый диапазон обсчитываем в отдельном потоке. А N - это число потоков.

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;
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.