synchronized thread execution

后端 未结 4 968
终归单人心
终归单人心 2021-01-22 17:27

my task is to create thread in this order: if A start->start B and C, if B start->start D. And destroy them in reverse order If D then B. If B and C then A. I hope you get it.

4条回答
  •  天命终不由人
    2021-01-22 17:57

    I would like to highlight two points here:

    1. Have a look at thread execution life cycle here. It says that, when start() method is called, thread enters in runnable state and not in running state. When thread enters in running state, that means run() method is getting exexuted. CPU/OS decides the priority of which thread should be transferred from runnable to running thread. E.g. if you call start() method for 4 threads, it is not necessary that they will execute in that particular order. (Running the same program in my pc multiple times gives me different outputs.

    In your case, when the condition if(thread_A.isAlive()) is executed, it is possible that the thread A may not be in running state. Hence, the control will not go into if which is not correct. To correct this behavior, in main, a while loop should implemented which waits until the thread becomes alive and so on.

    2 . In your program, you have not assigned names to the threads and you are printing the name in the run() method. In this case, JVM assigns the names to threads in order of their execution e.g. first thread to execute will have name as 'Thread-0' and so on. Hence, we will not be able to identify which thread executed first. Assign the names using setName() method.

提交回复
热议问题