Is the next thread safe? 4 streams that are written to the same data structure

So, let's say I have 4 threads, and they all go through an array with 100 indices, flipping a bit of information in each index and writing back that index ...

arr[];

Thread 1:

for (int i = 0; i< 100; i+=4) { flip bits of arr[i]}

Thread 2:

for (int j = 1; j< 100; j+=4) { flip bits of arr[j]}

Thread 3:

for (int k = 2; k< 100; k+=4) { flip bits of arr[k]}

Thread 4:

for (int l = 3; l< 100; l+=4) { flip bits of arr[l]}

I'm a complete noob in concurrency, so I was wondering if this was good practice or was there another way to do this?

UPDATE: , - - "flip bits of arr [i]" "flip bits of arr [j]" /, " " ( ), , j , .

+4
3

, , .


:

  • : int[] arr = new int[100]; //populate array
  • t.start() T1, T2, T3, T4 , , , ( - 4 for)
  • t.join() T1, T2, T2, T4

:

  • 2, T1..T4 - ,
  • , int,
  • ( 2) : , , T1, T1 - ,
  • "" - .

.

, , , , .

, 25 int, , , , , . , (, ExecutorService), , .

, java 8 , :

IntStream.range(0, arr.length).parallel()
         .forEach(i -> flip(arr[i]));

, , , , ...


:

+5

, . , . 0-24 A, 25-49 B .. , .

+1

, . ( Java, , , , ). .

arr.

, arr .

.

, ( concurrency).

arr. arr, , , arr.

for for.

, .


P.S.: , arr , arr, , , . .

0

All Articles