Getting different thread order even time I run my program

后端 未结 3 1835
醉梦人生
醉梦人生 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.

提交回复
热议问题