How to make two threads in turn, changing the arraist?

The code you see below tries to achieve the following:

  • add string "0" to arraylist
  • print the last element in arraylist, i.e. "line 0"
  • remove last item from arraylist

  • add line 1 to arraylist

  • print the last element in arraylist, i.e. "line 1" remove the last element from arraylist

... etc. without end.

So the conclusion I expect is simple:

line 0

line 1

..

..

However, I get a random number of "lines i", where I am also random. Here's an example output:

Line 0

Line 38919

Line 47726

Line 54271

, , , "hold" true false, .

import java.util.*;

public class Test {

     static boolean held = true;
     static ArrayList<String> line = new ArrayList<>();


     public static void main(String[] args) {

        new Thread() {
            @Override
            public void run() {
                int i = 0;
                while(true) {
                    if(held) {
                        line.add("Line " + i);
                        i++;
                        held = false;
                    }
                }
            }


        }.start();

        while(true) {
            if(!held) {
                System.out.println( line.get(line.size() - 1) );
                line.remove(line.size() - 1);
                held = true;

            }else continue;
        }

    }


}
+4
4

, held volatile . , . , , , . AtomicBoolean .

+6

-, : ( ) , while. , , , , . .

-, while , , , , .

+1

, , , wait , , .

0

I think it's better to use a synchronized list instead of an arraylist for this scenario :

List line = Collections.synchronizedList(new ArrayList(...));
0
source

Source: https://habr.com/ru/post/1569161/


All Articles