-4

Which two are possible results? (Select two)

public class Cruiser {

    private int a = 0;

    public void foo() {
        Runnable r = new LittleCruiser();
        new Thread(r).start();
        new Thread(r).start();
    }

    public static void main(String arg[]) {
        Cruiser c = new Cruiser();
        c.foo();
    }

    public class LittleCruiser implements Runnable {
        public void run() {
            int current = 0;
            for (int i = 0; i < 4; i++) {
                current = a;
                System.out.print(current + ", ");
                a = current + 2;
            }
        }
    }
}
  • A) 0, 2, 4, 0, 2, 4, 6, 6,
  • B) 0, 2, 4, 6, 8, 10, 12, 14,
  • C) 0, 2, 4, 6, 8, 10, 2, 4,
  • D) 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
  • E) 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,

The correct answers are A and B, however I don't really understand how this code generated A on lower level.

Impurity
  • 1,037
  • 2
  • 16
  • 31
  • Hi Daria - welcome to Stack Overflow. Asking homework questions here is welcome if you're showing the work that you've already done (rather than just asking for the answer). See the help center here: https://stackoverflow.com/help/on-topic – dwjohnston Aug 22 '18 at 11:45
  • As an aside, I think this code couldn't ever produce any output at all because it won't even compile. The public class LittleCruiser is required to be defined in its own source file. – Erwin Smout Aug 22 '18 at 11:47
  • @ErwinSmout Java allows inner classes – 3mpty Aug 22 '18 at 12:37
  • @ErwinSmout oh well bbe try to run it on Intellij Idea and u'll see that both outputs A and B are possible + a few more. – Daria Kostenko Aug 22 '18 at 12:41

1 Answers1

0

A) 0, 2, 4, 0, 2, 4, 6, 6,

Thread-1: read a = 0;
Thread-2: read a = 0;
Thread-1: output 0, 2, 4 
Thread-2: output 0
Thread-2: write 2 back to a
Thread-2: output 2, 4, 6
Thread-2: write 6 back to a;
Thread-1: read a = 6 and output 6
Hearen
  • 7,420
  • 4
  • 53
  • 63