Java Multithreading 4: yield
This blog will introduce the yield() method in Thread . The content involved includes:
- Introduction to yield()
- yield() example
- Comparison of yield() and wait()
Introduction to yield()
The effect of yield() is to give in. It can make the current thread enter the runnable state from the running state , so that other waiting threads with the same priority can obtain execution rights. However, there is no guarantee that after the current thread calls yield() , others have the same priority will be able to obtain the execution right. It may also be that the current thread enters the running state and continues to run!
yield() example
One of the possible result:
t1 did not switch to t2 when it could be divided by 4. This shows that although yield() can make the thread enter the runnable state from the running state , it does not necessarily allow other threads to obtain CPU execution rights (that is, other threads enter the running state ), even if other threads have the same priority as the thread currently calling yield() .
Comparison of yield() and wait()
We know that wait() will let the current thread enter the blocked state (wait) from the running state , and also release the synchronization lock. yield() will also make the current thread leave the running state . The difference is:
Thread yield java что это
In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three.
We can prevent the execution of a thread by using one of the following methods of the Thread class. All three methods will be used to prevent the thread from execution.
1. yield() Method
Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its execution and thread t2 and t3 are in Ready/Runnable state. The completion time for thread t1 is 5 hours and the completion time for t2 is 5 minutes. Since t1 will complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one thread is taking too much time to complete its execution, we need a way to prevent the execution of a thread in between if something important is pending. yield() helps us in doing so.
The yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.

Use of yield method:
- Whenever a thread calls java.lang.Thread.yield method gives hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint.
- If any thread executes the yield method, the thread scheduler checks if there is any thread with the same or high priority as this thread. If the processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give the processor to another thread and if not – the current thread will keep executing.
- Once a thread has executed the yield method and there are many threads with the same priority is waiting for the processor, then we can’t specify which thread will get the execution chance first.
- The thread which executes the yield method will enter in the Runnable state from Running state.
- Once a thread pauses its execution, we can’t specify when it will get a chance again it depends on the thread scheduler.
- The underlying platform must provide support for preemptive scheduling if we are using the yield method.
2. sleep() Method
This method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Class Thread
Thread defines constructors and a Thread.Builder PREVIEW to create threads. Starting a thread schedules it to execute its run method. The newly started thread executes concurrently with the thread that caused it to start.
A thread terminates if either its run method completes normally, or if its run method completes abruptly and the appropriate uncaught exception handler completes normally or abruptly. With no code left to run, the thread has completed execution. The join method can be used to wait for a thread to terminate.
Threads have a unique identifier and a name. The identifier is generated when a Thread is created and cannot be changed. The thread name can be specified when creating a thread or can be changed at a later time.
Threads support ThreadLocal variables. These are variables that are local to a thread, meaning a thread can have a copy of a variable that is set to a value that is independent of the value set by other threads. Thread also supports InheritableThreadLocal variables that are thread local variables that are inherited at Thread creation time from the parent Thread. Thread supports a special inheritable thread local for the thread context-class-loader.
Platform threads
Thread supports the creation of platform threads that are typically mapped 1:1 to kernel threads scheduled by the operating system. Platform threads will usually have a large stack and other resources that are maintained by the operating system. Platforms threads are suitable for executing all types of tasks but may be a limited resource.
Platform threads get an automatically generated thread name by default.
Platform threads are designated daemon or non-daemon threads. When the Java virtual machine starts up, there is usually one non-daemon thread (the thread that typically calls the application’s main method). The shutdown sequence begins when all started non-daemon threads have terminated. Unstarted non-daemon threads do not prevent the shutdown sequence from beginning.
In addition to the daemon status, platform threads have a thread priority and are members of a thread group.
Virtual threads
Thread also supports the creation of virtual threads. Virtual threads are typically user-mode threads scheduled by the Java runtime rather than the operating system. Virtual threads will typically require few resources and a single Java virtual machine may support millions of virtual threads. Virtual threads are suitable for executing tasks that spend most of the time blocked, often waiting for I/O operations to complete. Virtual threads are not intended for long running CPU intensive operations.
Virtual threads typically employ a small set of platform threads used as carrier threads. Locking and I/O operations are examples of operations where a carrier thread may be re-scheduled from one virtual thread to another. Code executing in a virtual thread is not aware of the underlying carrier thread. The currentThread() method, used to obtain a reference to the current thread, will always return the Thread object for the virtual thread.
Virtual threads do not have a thread name by default. The getName method returns the empty string if a thread name is not set.
Virtual threads are daemon threads and so do not prevent the shutdown sequence from beginning. Virtual threads have a fixed thread priority that cannot be changed.
Creating and starting threads
Thread defines public constructors for creating platform threads and the start method to schedule threads to execute. Thread may be extended for customization and other advanced reasons although most applications should have little need to do this.
Thread defines a Thread.Builder PREVIEW API for creating and starting both platform and virtual threads. The following are examples that use the builder:
Inheritance when creating threads
Platform threads inherit the daemon status, thread priority, and when not provided (or not selected by a security manager), the thread group.
Creating a platform thread captures the caller context to limit the permissions of the new thread when it executes code that performs a privileged action. The captured caller context is the new thread’s «Inherited AccessControlContext «. Creating a virtual thread does not capture the caller context; virtual threads have no permissions when executing code that performs a privileged action.
Unless otherwise specified, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
Nested Class Summary
Field Summary
Constructor Summary
Method Summary
Methods declared in class java.lang.Object
Field Details
MIN_PRIORITY
NORM_PRIORITY
MAX_PRIORITY
Constructor Details
Thread
This constructor is only useful when extending Thread to override the run() method.
Thread
For a non-null task, invoking this constructor directly is equivalent to:
Thread
For a non-null group and task, invoking this constructor directly is equivalent to:
Thread
This constructor is only useful when extending Thread to override the run() method.
Thread
This constructor is only useful when extending Thread to override the run() method.
Thread
For a non-null task and name, invoking this constructor directly is equivalent to:
Thread
If there is a security manager, its checkAccess method is invoked with the ThreadGroup as its argument.
In addition, its checkPermission method is invoked with the RuntimePermission(«enableContextClassLoaderOverride») permission when invoked directly or indirectly by the constructor of a subclass which overrides the getContextClassLoader or setContextClassLoader methods.
The priority of the newly created thread is the smaller of priority of the thread creating it and the maximum permitted priority of the thread group. The method setPriority may be used to change the priority to a new value.
The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.
For a non-null group, task, and name, invoking this constructor directly is equivalent to:
Thread
This constructor is identical to Thread(ThreadGroup,Runnable,String) with the exception of the fact that it allows the thread stack size to be specified. The stack size is the approximate number of bytes of address space that the virtual machine is to allocate for this thread’s stack. The effect of the stackSize parameter, if any, is highly platform dependent.
On some platforms, specifying a higher value for the stackSize parameter may allow a thread to achieve greater recursion depth before throwing a StackOverflowError . Similarly, specifying a lower value may allow a greater number of threads to exist concurrently without throwing an OutOfMemoryError (or other internal error). The details of the relationship between the value of the stackSize parameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of the stackSize parameter may have no effect whatsoever.
The virtual machine is free to treat the stackSize parameter as a suggestion. If the specified value is unreasonably low for the platform, the virtual machine may instead use some platform-specific minimum value; if the specified value is unreasonably high, the virtual machine may instead use some platform-specific maximum. Likewise, the virtual machine is free to round the specified value up or down as it sees fit (or to ignore it completely).
Specifying a value of zero for the stackSize parameter will cause this constructor to behave exactly like the Thread(ThreadGroup, Runnable, String) constructor.
Due to the platform-dependent nature of the behavior of this constructor, extreme care should be exercised in its use. The thread stack size necessary to perform a given computation will likely vary from one JRE implementation to another. In light of this variation, careful tuning of the stack size parameter may be required, and the tuning may need to be repeated for each JRE implementation on which an application is to run.
Implementation note: Java platform implementers are encouraged to document their implementation’s behavior with respect to the stackSize parameter.
For a non-null group, task, and name, invoking this constructor directly is equivalent to:
Thread
This constructor is identical to Thread(ThreadGroup,Runnable,String,long) with the added ability to suppress, or not, the inheriting of initial values for inheritable thread-local variables from the constructing thread. This allows for finer grain control over inheritable thread-locals. Care must be taken when passing a value of false for inheritThreadLocals , as it may lead to unexpected behavior if the new thread executes code that expects a specific thread-local value to be inherited.
Specifying a value of true for the inheritThreadLocals parameter will cause this constructor to behave exactly like the Thread(ThreadGroup, Runnable, String, long) constructor.
For a non-null group, task, and name, invoking this constructor directly is equivalent to:
Method Details
currentThread
yield
Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.
sleep
sleep
sleep
onSpinWait
The code above would remain correct even if the onSpinWait method was not called at all. However on some architectures the Java Virtual Machine may issue the processor instructions to address such code patterns in a more beneficial way.
ofPlatform
Creating a platform thread when there is a security manager set will invoke the security manager’s checkAccess(ThreadGroup) method with the thread’s thread group. If the thread group has not been set with the OfPlatform.group PREVIEW method then the security manager’s getThreadGroup method will be invoked first to select the thread group. If the security manager getThreadGroup method returns null then the thread group of the constructing thread is used.
ofVirtual
clone
startVirtualThread
This method is equivalent to:
isVirtual
start
A thread can be started at most once. In particular, a thread can not be restarted after it has terminated.
This method is not intended to be invoked directly. If this thread is a platform thread created with a Runnable task then invoking this method will invoke the task’s run method. If this thread is a virtual thread then invoking this method directly does nothing.
interrupt
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait() , wait(long) , or wait(long, int) methods of the Object class, or of the join() , join(long) , join(long, int) , sleep(long) , or sleep(long, int) methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException .
If this thread is blocked in an I/O operation upon an InterruptibleChannel then the channel will be closed, the thread’s interrupt status will be set, and the thread will receive a ClosedByInterruptException .
If this thread is blocked in a Selector then the thread’s interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector’s wakeup method were invoked.
If none of the previous conditions hold then this thread’s interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
interrupted
isInterrupted
isAlive
suspend
resume
setPriority
getPriority
The priority of a virtual thread is always NORM_PRIORITY .
setName
First the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException .
getName
getThreadGroup
The thread group returned for a virtual thread is the special ThreadGroup for virtual threads.
activeCount
The value returned is only an estimate because the number of threads may change dynamically while this method traverses internal data structures, and might be affected by the presence of certain system threads. This method is intended primarily for debugging and monitoring purposes.
enumerate
An application might use the activeCount method to get an estimate of how big the array should be, however if the array is too short to hold all the threads, the extra threads are silently ignored. If it is critical to obtain every live thread in the current thread’s thread group and its subgroups, the invoker should verify that the returned int value is strictly less than the length of tarray .
Due to the inherent race condition in this method, it is recommended that the method only be used for debugging and monitoring purposes.
countStackFrames
An invocation of this method behaves in exactly the same way as the invocation
This method does not wait if the duration to wait is less than or equal to zero. In this case, the method just tests if the thread has terminated.
dumpStack
setDaemon
The daemon status of a virtual thread is always true and cannot be changed by this method to false .
This method must be invoked before the thread is started. The behavior of this method when the thread has terminated is not specified.
isDaemon
checkAccess
If there is a security manager, its checkAccess method is called with this thread as its argument. This may result in throwing a SecurityException .
toString
getContextClassLoader
The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.
setContextClassLoader
The context ClassLoader may be set by the creator of the thread for use by code running in this thread when loading classes and resources.
The context ClassLoader cannot be set when the thread is not allowed PREVIEW to have its own copy of thread local variables.
If a security manager is present, its checkPermission method is invoked with a RuntimePermission («setContextClassLoader») permission to see if setting the context ClassLoader is permitted.
holdsLock
This method is designed to allow a program to assert that the current thread already holds a specified lock:
getStackTrace
If there is a security manager, and this thread is not the current thread, then the security manager’s checkPermission method is called with a RuntimePermission(«getStackTrace») permission to see if it’s ok to get the stack trace.
Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.
getAllStackTraces
The threads may be executing while this method is called. The stack trace of each thread only represents a snapshot and each stack trace may be obtained at different time. A zero-length array will be returned in the map value if the virtual machine has no stack trace information about a thread.
If there is a security manager, then the security manager’s checkPermission method is called with a RuntimePermission(«getStackTrace») permission as well as RuntimePermission(«modifyThreadGroup») permission to see if it is ok to get the stack trace of all threads.
getId
threadId
getState
setDefaultUncaughtExceptionHandler
Uncaught exception handling is controlled first by the thread, then by the thread’s ThreadGroup object and finally by the default uncaught exception handler. If the thread does not have an explicit uncaught exception handler set, and the thread’s thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler’s uncaughtException method will be invoked.
By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that would already accept whatever "default" behavior the system provided.
Note that the default uncaught exception handler should not usually defer to the thread’s ThreadGroup object, as that could cause infinite recursion.
getDefaultUncaughtExceptionHandler
getUncaughtExceptionHandler
setUncaughtExceptionHandler
A thread can take full control of how it responds to uncaught exceptions by having its uncaught exception handler explicitly set. If no such handler is set then the thread’s ThreadGroup object acts as its handler.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Жизненный цикл потока в Java

Эта статья направлена на объяснение различных состояний потока в мире Java. Если вы новичок в области многопоточного программирования, попробуйте сначала почитать про потоки что-нибудь базовое.
Согласно Sun Microsystems, существует четыре состояния жизненного цикла потока Java. Вот они:
- New — поток находится в состоянии New , когда создается экземпляр объекта класса Thread , но метод start не вызывается.
- Runnable — когда для объекта Thread был вызван метод start . В этом состоянии поток либо ожидает, что планировщик заберет его для выполнения, либо уже запущен. Назовем состояние, когда поток уже выбран для выполнения, “работающим” ( running).
- Non-Runnable(Blocked , Timed-Waiting) — когда поток жив, то есть объект класса Thread существует, но не может быть выбран планировщиком для выполнения. Он временно неактивен.
- Terminated — когда поток завершает выполнение своего метода run , он переходит в состояние terminated (завершен). На этом этапе задача потока завершается.
Ниже дано схематическое представление жизненного цикла потока в Java:
Рис. 1 — Жизненный цикл Java-потока
Минуточку! Звучит замечательно, но что это за “планировщик” такой? Я вызвал метод start , так почему бы системе просто не запустить мой поток, а не ждать в рабочем состоянии, пока планировщик его подберет?
Хороший вопрос! Планировщик — это программное обеспечение, которое используется для отслеживания задач компьютера. Он отвечает за назначение задач ресурсам, которые могут совершать работу. Мы не будем углубляться в логику, которую реализует планировщик. На данный момент достаточно знать, что планировщик имеет контроль над тем, какая задача должна быть назначена какому аппаратному ресурсу и когда, исходя из доступности ресурса и состояния задачи.
Выходит, планировщик решает, когда назначить задачу требуемому ресурсу. Но как задача переходит в нерабочее состояние? Как и почему поток должен отказаться от процессорного времени и приостановить выполнение? Это происходит по выбору или вынужденно?
Что же. Поток может находиться в нерабочем состоянии по разным причинам — иногда принудительно, иногда по собственному выбору. Вынужденные причины могут заключаться в том, что он ожидает операции ввода-вывода, например получения сообщения по порту, или он может ждать объект, который удерживается другим потоком. Последний сценарий приводит к появлению синхронизированного объекта. Когда поток обращается к синхронизированному объекту, он создает блокировку на этом объекте. Блокировка — это что-то вроде временного контракта между потоком и объектом, который дает потоку эксклюзивный доступ к объекту, запрещая доступ любому другому потоку. Для обеспечения этого контракта Java связывает с каждым объектом монитор. Поток также может быть перемещен планировщиком в нерабочее состояние (спящий режим) на основе логики совместного использования ресурсов планировщика.
Потоки могут перейти в нерабочее состояние по выбору. То есть по выбору программиста. Программист может написать метод потока ( run или любой другой метод, который вызывается внутри run ) таким образом, чтобы тот намеренно уступал процессорное время. Так делается, чтобы получить максимальную отдачу от доступных вычислительных мощностей или вызвать задержки после выполнения определенной части потока. Давайте посмотрим, какие методы добровольного отказа от процессорного времени нам доступны:
- sleep(long millis) — этот метод инициирует у вызывающего потока спящий режим на время, указанное в качестве параметра. Важно отметить, что при вызове sleep поток отдает процессорное время, но блокировка объектов не отменяются. После выхода из спящего режима поток возвращается в рабочее состояние, ожидая, пока планировщик заберет его для выполнения. Это обычно применяется для вызова задержки в части выполнения потока.
- wait() или wait(long timeout) — этот метод заставляет поток отказаться от процессорного времени, а также снять любые блокировки объектов. Он может быть вызван с параметром timeout . При вызове без тайм-аута поток остается в неработающем состоянии бесконечно, пока другой поток не вызовет метод notify() или notifyAll() . При вызове с параметром timeout поток ожидает не более продолжительности тайм-аута, а затем автоматически переходит в состояние runnable . Этот метод необходим в ситуациях, когда несколько потоков должны работать синхронно.
- yield() — этот метод представляет собой своего рода уведомление планировщика о том, что поток готов отказаться от выполнения. Затем планировщик, основываясь на других имеющихся потоках и их приоритетах, решает: хочет ли он переместить вызывающий поток в состояние runnable и предоставить процессорное время другим потокам или продолжать выполнять существующий поток. Лично мне этот метод кажется весьма полезным. Если мы знаем, что выполнение метода/функции займет много времени и что задача не является срочной, мы можем написать ее со стратегически расположенными вызовами метода yield , чтобы планировщик мог использовать процессор для выполнения потоков с более высоким приоритетом и более коротким временем выполнения.
- join() — вызывается для приостановки выполнения программы до тех пор, пока поток, вызывающий метод join , не будет завершен.
Время запачкать руки! Напишем-ка небольшой код, чтобы создать пару потоков и проверить их состояние на протяжении всего выполнения.
Простое выполнение единственного потока
Этот код выведет следующее:
Рис. 2 — Вывод кода
Давайте попробуем понять, что здесь происходит.
Функция printThreadState выводит текущее состояние потока. Впервые она вызывается после создания экземпляра объекта Thread , и ее вывод соответствует тому, что мы узнали недавно. Поток оказался в состоянии new . Теперь внимательно наблюдайте за выводом.
После метода start мы выполнили метод printThreadState , и поток перешел в состояние runnable . Это происходит до того, как планировщик передал поток для выполнения, потому что если бы поток уже был запущен, мы получили бы в выводе инструкцию print , написанную внутри метода run класса Thread1 . Отсюда можно видеть, что поток выполняется.
Обратите внимание, что поток так и находится в состоянии runnable , поскольку, как упоминалось в начале этой статьи, Java определяет только четыре состояния в жизненном цикле потока. Состояние running фигурирует в этой статье только для упрощения понимания.
Наконец, после завершения выполнения метода run , поток тоже завершается, а затем уничтожается. Циклы for в программе существуют только затем, чтобы дать потоку достаточно времени для завершения выполнения.
2. Выполнение нескольких потоков
1. Влияние синхронизации
Теперь давайте рассмотрим сценарии с синхронизированными блоками кода. Мы напишем программу для запуска двух потоков, которые пытаются получить доступ к одному и тому же экземпляру класса. Мы запустим программу дважды: один раз без ключевого слова synchronized в объявлении метода и один раз с ключевым словом synchronized .
На рис. 3 показан вывод без ключевого слова synchronized, а на рис. 4 — с ключевым словом synchronized.
Рис.3 — вывод для несинхронизированного выполнения потоков
Рис.4 — вывод для синхронизированного выполнения потоков
Почему вывод такой рандомный?
Потому что два потока выполняются параллельно. Обратите внимание: статус блокировки потоков четко false , поэтому любой поток может получить доступ к объекту в одно время.
А поскольку мы использовали ключевое слово synchronized для получения вывода на рис.4, то первый поток, получивший доступ к объекту, удерживал его блокировку. Это преграждало другому потоку доступ к объекту до завершения выполнения первого потока.
2. Методы “sleep” и “yield”
Измените код в файлах SynchronizationDemo.java и Persons.java , как показано в вышеприведенном фрагменте кода. Запустите код как в синхронизированном, так и в несинхронизированном режимах. Мы переводим первый поток в спящий режим на две секунды, как только начинается его выполнение.
Рис. 5 — Вывод для несинхронизированного выполнения потоков
Как и ожидалось, в несинхронизированном режиме оба потока не удерживают никакой блокировки на объекте. FirstThread переходит в Timed_Waiting при вызове метода sleep . Второй поток продолжает выполнение, так как нет блокировки его доступа к объекту.
Рис. 6 — Вывод для синхронизированного выполнения потоков
В синхронизированном режиме потоки удерживают блокировки, и поэтому, даже когда первый поток находится в состоянии Timed_Waiting , второй поток все равно не может получить доступ к объекту.
Теперь замените метод sleep на yield и удалите блок try-catch в файле Persons.java . Результат будет таким же, как и в разделе 2.1. Этот метод будет полезен для задач, требующих больших вычислительных мощностей, но меньшей срочности.
3. Методы “wait” и “notify”
Что делать, если мы не хотим, чтобы поток заканчивал выполнение, пока какой-то другой поток не скажет ему продолжить?
Допустим, у нас есть учетная запись у поставщика широкополосных сетевых услуг и мы хотим добавить на баланс еще данных. Если у нашей учетной записи недостаточно средств, мы не сможем пополнить счет для передачи данных. Таким образом, поставщик услуг будет ждать, пока мы добавим на аккаунт средства, чтобы завершить дозакупку. Давайте взглянем на код.
Вывод без join :
Person [name=Rajat, job=null, address=Dublin]
Вывод с join :
Person [name=Rajat, job=Software Developer, address=Dublin]
Обратите внимание на результаты и сравните их. Я добавил метод sleep в поток Job , чтобы увеличить время выполнения и более наглядно продемонстрировать результаты. Без вмешательства join , выполнение не ждет, когда потоки завершат выполнение, и создает объект Person . В результате объект содержит значение null в атрибуте job . Тогда как, когда мы использовали метод join , все отработало гладко. Проще говоря, распараллеливание задач, требующих большой вычислительной мощности, сокращает общее время выполнения, но надо быть осторожным, чтобы в процессе не потерять какую-то информацию. Метод join — один из лучших инструментов для этого.
Занимаясь многопоточным программированием, я провел много лет в поисках идеального способа реализации, и это было трудно. Итак, я попытался объяснить вам многопоточное программирование. Рекомендую поиграть с кодом из этой статьи, чтобы исследовать его глубже и укрепить свое понимание предмета.