Execution order of multiple threads

前端 未结 4 1784
失恋的感觉
失恋的感觉 2020-12-03 16:43

Let\'s say we have this scenario:

class Stack{

public void main{

ChildThread1 t1 = new ChildThread1;
ChildThread1 t2 = new ChildThread1;
ChildThread1 t3 =          


        
4条回答
  •  佛祖请我去吃肉
    2020-12-03 16:55

    The whole point of threads is that they can be executed concurrently. If you want to ensure specific order in which things are done, you either have to move away from using threads, or use explicit synchronization.

    So am I right to assume that this weird order of prints is because start() does not guarantee order of execution?

    That's right. When you start a thread, there's basically a race condition between the main thread and the newly created thread. This means that nothing can be said about the relative order in which things happen between the two threads. If you want to ensure specific ordering, use synchronization.

提交回复
热议问题