DEV Community

ChelseaLiu0822
ChelseaLiu0822

Posted on

start and run

If you use the run method directly, you cannot start a new thread. You must use the start method to start a thread.
The start method cannot be called multiple times. After the thread becomes runnable, it cannot be called again using start.

sleep and yield

sleep:

  1. Calling sleep will cause the current thread to enter the Timed_Waiting state from Running (blocking)
  2. Other threads can use the interrupt method to interrupt the sleeping thread, and the sleep method will throw InterruptedException
  3. The thread after sleeping may not be executed immediately
  4. It is recommended to use TimeUnit’s sleep instead of Thread’s sleep for better readability. yield:
  5. Calling yield will cause the current thread to enter the Runnable ready state from Running, and then schedule the execution of other threads. Procedure
  6. The specific implementation depends on the task scheduler of the operating system The task scheduler will not allocate time slices to threads in blocked state (Timed Waiting) Thread priority The thread priority will prompt the scheduler to schedule the thread first. It is just a prompt and can be ignored by the scheduler. When the CPU is relatively busy, threads with higher priority will get more time slices. When the CPU is relatively idle, threads with higher priority will get more time. Level has almost no effect setPriority()1-10, the default is 5, the bigger, the higher sleep application - prevent 100% CPU usage When the CPU is not used for calculations, do not let while (true) idle and waste the CPU. In this case, you can use yield or sleep to give CPU usage rights to other programs You can use wait or condition variables to achieve similar effects. The difference is that the latter two require locking and corresponding wake-up operations, which are generally suitable for scenarios where synchronization is required. ​

Top comments (0)