Abhilash28
Abhilash28

Reputation: 645

Java Multithread code behavior

For the below java code:

public class Chess implements Runnable {
    public void run() {
        move(Thread.currentThread().getId());
    }

    void move(long id) {
        System.out.print(id + " ");
        System.out.print(id + " ");
    }

    public static void main(String[] args) {
        Chess ch = new Chess();
        new Thread(ch).start();
        new Thread(new Chess()).start();
    }
}

One of the possible outcomes for this code is - output could be 4 2 4 2 (Or be it some other thread id other than 4, 2). can someone explain me how this is possible? Given the threads will run on different instances of "Chess" class, how do we get different id's printed here since both the S.O.P statements are printing the id's immediately and only these 2 threads would call the move method

Upvotes: 2

Views: 136

Answers (2)

MC Emperor
MC Emperor

Reputation: 23057

It's not that strange.

You are creating two threads, each one having a different id (2 and 4 respectively in your case). You are printing those ids twice, so each id gets printed twice.

So the different numbers and their occurrences are explained now.

And what about the order? Well, that's the thing about threads, they are executed by the processor(s) and you have no control over the order of execution per processor instruction.


PS: The number of Chess instances doesn't matter. If you should change the code to this:

Chess ch = new Chess();
new Thread(ch).start();
new Thread(ch).start();

it wouldn't matter.

Upvotes: 2

BSM
BSM

Reputation: 183

The "main" thread runs user created thread always. Here in your case "main"thread is responsible to run, new Thread(ch).start() //thread - 0 new Thread(new Chess()).start(); //thread - 1.

As above threads are having equal priority (5 by default), ThreadScehduler will schedule both the threads to run simultaneously. Hence you get Ids of two different threads.

You can synchronize on Chess class and run the threads, then you would get one thread ID printed at a time.

You can apply class level locking as below and have IDs printed one at a time,

public class Chess implements Runnable {
public void run() {
    move(Thread.currentThread().getId());
}

synchronized static void move(long id) {
    System.out.println(id + " ");
    System.out.println(id + " ");

}

public static void main(String[] args) {
    Chess ch = new Chess();
    new Thread(ch).start();
    new Thread(new Chess()).start();
}

}

Upvotes: 0

Related Questions