Why am I getting this output in this java thread program?

Hi, I am new to Java programming, recently I am studying Threads, I have a problem with the output of this program.

class s1 implements Runnable { int x = 0, y = 0; int addX() {x++; return x;} int addY() {y++; return y;} public void run() { for(int i = 0; i < 10; i++){ System.out.println(addX() + " " + addY()); } } public static void main(String args[]) { s1 run1 = new s1(); s1 run2 = new s1(); Thread t1 = new Thread(run1); Thread t2 = new Thread(run2); t1.start(); t2.start(); } } 

I get the output as follows:

1 1 2 2 1 1 3 3 ... please explain why?

+4
source share
3 answers

Threads are executed asynchronously - so their output will naturally intertwine, which can be expected. In your case:

1 1 2 2 1 1 3 3

... The bit that I selected is the output from one stream, the bit that I left equal is the (beginning) of output from another. I can only handle this because of how the program runs - if you had two threads that just printed the character "1", for example, it would be impossible to distinguish which thread printed which character.

Note that the order in which numbers appear and how they intertwine is completely arbitrary — it could be just as easy:

1 1 1 1 2 2 3 3 2 2 ..

... Or any other possible combination. Do not rely on what you get for any particular program, completely undefined.

+7
source

Each instance of class s1 has its own variables, so they will increase independently of each other. If you made only one instance, the output will be 1 1 2 2 3 3 ...

If you take two streams, each of which prints 1 1 2 2 3 3 ... , you will see that the two streams are mixed up. While it displays the correct amount of each number in the correct order, it does what you expect. You cannot expect how threads will execute.

So, you can see 1 1 2 2 3 3 1 1 2 2 3 3... or 1 1 1 1 2 2 2 2 3 3 3 3... or any other options.

(You might be lucky and see 1 1 1 1 2 2 2 2 3 3 3 3 ... one day if the planner cuts in a certain way)

EDIT: Also read this thread safety answer in a println call.

+5
source

Try executing this code:

 class Test extends Thread { Test(String name) { super(name); } int x = 0, y = 0; int addX() {x++; return x;} int addY() {y++; return y;} public void run() { for(int i = 0; i < 10; i++) System.out.println(addX() + " " + addY() + ", name:" + getName()); } public static void main(String args[]) { Test run1 = new Test("thread1"); Test run2 = new Test("thread2"); run1.start(); run2.start(); } } 

You will get a result similar to this:

 1 1, name:thread2 2 2, name:thread2 1 1, name:thread1 2 2, name:thread1 3 3, name:thread2 3 3, name:thread1 

This is because protectors are not executed synchronously. You do not know when this will be done. In your code, 1 1 , and then again 1 1 - this is just the output of two threads performing the same thing.

0
source

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


All Articles