0

Question2: I have almost same question but with Threads here is the code:

public class Example5 implements Runnable {
      static int a=0;

  public Example5() {
      a++;
  }
  public int getA() {
      return (a);
  }
  public void run() {
      System.out.println(getA());
  }

  public static void main(String[] s) {
      Example5 ex1 = new Example5();
      new Thread(ex1).start();

      Example5 ex2 = new Example5();
      new Thread (ex2).start();
  }
}

it says to me it must print: 1 or 2 2 anyone can explain this in threads.

Also anyone can explain to me what happen when i do for example(Not related to first question)

Thread t = new Thread();
t.start();
Thread t2 = new Thread();
t2.start();

Do they work sorted, (like first thread works first and then second thread) or it just goes randomly. thanks

akash
  • 22,664
  • 11
  • 59
  • 87
MaxDevelop
  • 637
  • 1
  • 4
  • 16
  • possible duplicate of [Java Thread Example?](http://stackoverflow.com/questions/2531938/java-thread-example) – Chetan Kinger Feb 28 '15 at 13:47
  • No i just posted again because its almost same but its another question because its with threads.. and work differently. – MaxDevelop Feb 28 '15 at 13:48
  • I tried to edit it and they told me you can't put another question in the first question that already answered.. – MaxDevelop Feb 28 '15 at 13:49

1 Answers1

0
Example5 ex1 = new Example5(); // a = 1
new Thread(ex1).start();  // start a new thread that will execute independently from current thread

Example5 ex2 = new Example5(); // a = 2 (a is static hence shared)
new Thread (ex2).start(); // start a new thread again

// thread1 and thread2 finish (the order is not determined - could be 
// thread2 first, then thread1)
// prints: 2 2
// If Thread1 finishes before the second "new Example5()" completes
// prints: 1 2

For the last question: kind of randomly. Since there is no synchronisation between your 3 threads (current, spawned thread1, spawn thread2).

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32
  • Thanks for second question :) for the first question in my solution it says 1 or 2 then 2, its like solution that can't have mistake – MaxDevelop Feb 28 '15 at 13:55
  • Yes it can be (2,2), or (1,2) if thread1 finishes first _before_ the second `new Example5` – T.Gounelle Feb 28 '15 at 13:57
  • So if thread 2 started then thread 1 it prints (2,2), because a is static? – MaxDevelop Feb 28 '15 at 14:07
  • If thread2 has started, it means `ex2` has been instantiated, hence `a=2`. But you have to be aware that operation like `System.out.println()` or even `a++` are not atomic. Since you increment `a` only in the current thread you will always have 2 at the end, but if you intend to do that in the spawned threads (without adequate synchronisation) you could end up with other results... – T.Gounelle Feb 28 '15 at 14:39