Does the ability to synchronize the increment of a variable exist, so that picking up the values ​​of i the thread will work with it further along the code, and the next thread would use the variable i with the next value (i + 1). Ie there is a loop and the threads in it should work with ArrayList elements:

for ( int i = 0; i < arrayList.size(); i++) { System.out.println(arrayList.get(i)); newArrayList.add(arrayList.get(i)); } 

The problem is that it is impossible to force the threads to miss the unique values ​​of i, and the threads work with the same data ...

  • 2
    If you need to synchronize a variable of type int, then use the class java.concurrent.atomic.AtomicInteger - ArchDemon
  • Can declare it final? - Nikolai Belyakov

1 answer 1

The threads themselves can increment the variable and select the desired element of the array.
If for simplicity, the workflows are disposable, and the array in the process does not change, then you can do it this way:

  // создаСм массив с Π΄Π°Π½Π½Ρ‹ΠΌΠΈ (Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ с числами 1-100) ArrayList<Integer> list = new ArrayList<>(); for (int i=1; i<=100; i++) list.add(i); // объявляСм ΠΈ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ ΠΏΠΎΡ‚ΠΎΠΊΠΎΠ±Π΅Π·ΠΎΠΏΠ°ΡΠ½ΡƒΡŽ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ счСтчика final AtomicInteger n = new AtomicInteger(-1); // описываСм ΠΏΠΎΡ‚ΠΎΠΊ ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π±ΡƒΠ΄Π΅Ρ‚ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ с элСмСнтом массива Runnable r = new Runnable() { @Override public void run() { int element = list.get(n.incrementAndGet()); // ΠΏΠΎΡ‚ΠΎΠΊ Π±ΡƒΠ΄Π΅Ρ‚ ΡΠ°ΠΌΠΎΡΡ‚ΠΎΡΡ‚Π΅Π»ΡŒΠ½ΠΎ ΠΈΠ½ΠΊΡ€Π΅ΠΌΠ΅Π½Ρ‚ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ счСтчик System.out.println(Thread.currentThread().getName() + " get element " + element); // ΠΈ Ρ‡Ρ‚ΠΎ Ρ‚ΠΎ Π΄Π΅Π»Π°Ρ‚ΡŒ с элСмСнтом } }; // запускаСм ΠΏΠΎΡ‚ΠΎΠΊΠΈ ΠΏΠΎ количСству элСмСнтов массива ExecutorService service = Executors.newFixedThreadPool(5); for (int i=0; i<list.size(); i++){ service.submit(r); } service.shutdown(); // Π΄Π°Π΅ΠΌ всСм ΠΏΠΎΡ‚ΠΎΠΊΠ°ΠΌ Π΄ΠΎΡ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ