Getting different thread order even time I run my program

后端 未结 3 1836
醉梦人生
醉梦人生 2021-01-22 09:28

can someone tell me the order in which a thread starts to execute?. I have written the following code

class NewThread implements Runnable {
    Thread t;
    New         


        
相关标签:
3条回答
  • 2021-01-22 09:40

    when I execute this code, I get many different sets of output.

    This is expected. The order is not defined and is subject to race conditions as the threads start running and are subjected to thread scheduling by the OS.

    The whole reason why we write multi-threaded applications is that the threads are asynchronous and run in separate processors for speed reasons. To guarantee specific output order, you could synchronize between the threads with locks and the like but you would then lose performance and the whole reason for forking threads would be diminished.

    0 讨论(0)
  • 2021-01-22 09:50

    There is no implicit order. If you must have an order, use the ExecutorService with a que depth of 1.

    0 讨论(0)
  • 2021-01-22 09:55

    You have encountered a race condition.

    You have stumbled across one of the complexities of multi-threading. If you have code that MUST be processed in a particular order you must "lock" that code and/or declare variables within it "volatile". Run a google search for "deadlocks" and "race conditions".

    0 讨论(0)
提交回复
热议问题