- What are the thread priorities?
The answer to this question is in the CodeGym lectures.
To optimize the parallel operation of threads in Java, it is possible to set thread priorities. Higher priority threads have an advantage in getting CPU time over lower priority threads.
Work with priorities is provided by the following class methods
Thread
:public final void setPriority(int newPriority)
Sets the priority of a thread.
public final int getPriority()
Lets you know the priority of a thread.
The value of a parameter in a method
setPriority
cannot be arbitrary. It must be between MIN_PRIORITY and MAX_PRIORITY . When a thread is created, it has a priority of NORM_PRIORITY .MIN_PRIORITY = 1.
NORM_PRIORITY = 5.
MAX_PRIORITY = 10. -
Is it possible to stop a thread by lowering its priority to 0?
The answer is in the article: “Top 50 interview questions. Topic: Multithreading (Multithreading)»
Found on the forum.
There is an English version of this article: Top 50 Java Thread Interview Questions Answers for Freshers, Experienced Programmers
Java provides rich APIs for everything, but ironically doesn't provide a convenient way to stop a thread. There were several control methods in JDK 1.0, such as
stop()
,suspend()
andresume()
, which were marked deprecated in future releases due to potential deadlock threats, since then the Java API developers have made no attempt to provide a robust, thread-safe, and elegant way to stop threads. Programmers mostly rely on the fact that a thread stops itself as soon as it finishes executing methodsrun()
orcall()
. To stop manually, programmers take advantage ofvolatile boolean
the variable and check its value in each iteration ifrun()
there are loops in the method, or break the threads with the methodinterrupt()
to abruptly cancel jobs.Specifically on the question: Nowhere have I seen someone set the priority to 0.
If anyone knows anything about this, then write in the comments.
-
Why is a class needed
ThreadGroup
?ThreadGroup
is a set of threads that can also contain other groups of threads. A group of threads forms a tree in which every other group of threads has a parent (except the original one). A thread has the right to access data from its thread group, but does not have such access to other groups or to the parent thread group. -
What group of threads does it belong to
main-thread
?I couldn't find it anywhere)) Tell me where it is))
-
What is a pattern
ThreadPool
?This is an excerpt from the Wikipedia article:
In computer programming, the thread pool pattern (also replicated workers or worker-crew model) is where a number of threads are created to perform a number of tasks, which are usually organized in a queue. The results from the tasks being executed might also be placed in a queue, or the tasks might return no result (for example, if the task is for animation). Typically, there are many more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available.
The number of threads used is a parameter that can be tuned to provide the best performance. Additionally, the number of threads can be dynamic based on the number of waiting tasks. For example, a web server can add threads if numerous web page requests come in and can remove threads when those requests taper down. The cost of having a larger thread pool is increased resource usage. The algorithm used to determine when to create or destroy threads will have an impact on the overall performance:
- create too many threads, and resources are wasted and time also wasted creating any unused threads
- destroy too many threads and more time will be spent later creating them again
- creating threads too slowly might result in poor client performance (long wait times)
In computer programming, there is a thread pool model, where a certain number of threads are created to perform a number of tasks, which are usually organized in a queue. Results from completed tasks may also be queued, or tasks may not return any result (for example, if the task is to be animated).
Typically, there are many more tasks than threads. Once a thread has completed its task, it will request the next task from the queue until all tasks have completed. The thread may then be interrupted or go to sleep. The number of threads to use is a parameter that can be adjusted to provide the best performance. In addition, the number of threads can be dynamic based on the number of tasks that occur. For example, a web server can add threads when requests for multiple web pages come in, and can remove threads when there are fewer requests. As the size of the thread pool increases, the use of computer resources increases. The algorithm used to determine when to create or destroy threads will have an impact on overall performance:
Destroy too many threads and more time will be spent later re-creating them - Creating threads too slowly can degrade client performance.
-
Why is a class needed
ThreadPoolExecutor
?public class ThreadPoolExecutor extends AbstractExecutorService
ExecutorService
it executes each submitted task using one possibly of several pooled threads, usually configured usingExecutors
factory methods.Thread pools address two distinct issues: they generally provide improved performance when running large numbers of asynchronous tasks due to reduced per-task call overhead, and they provide a means of limiting and managing resources, including the threads used by executing a set of tasks. Each
ThreadPoolExecutor
also supports some basic statistics such as the number of completed tasks.To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility levers. However, programmers are urged to use the more convenient
Executors
factory methodsExecutors.newCachedThreadPool()
(unrestricted thread pool, with automatic thread recovery),Executors.newFixedThreadPool(int)
(fixed-size thread pool), andExecutors.newSingleThreadExecutor()
(single background thread), which preconfigure the settings for the most common use cases. -
How many ways to create a thread do you know?
At the language level, there are two ways to create a thread. The class object
java.lang.Thread
is a thread, but it needs a task to execute, which is an object that implements thejava.lang.Runnable
. Since a classThread
implements an interfaceRunnable
, you can override a methodrun()
by deriving your class fromThread
or by implementing the interface in itRunnable
. -
What is the class used for
Future
?Future
stores the result of an asynchronous computation. You can start a calculation by giving someone an objectFuture
and forget about it. The owner of the objectFuture
can receive the result when it is ready. -
What are the advantages
Callable
overRunnable
?Reference: Part 2: Executing Tasks in Multithreaded Mode
An interface
Callable
is much more suitable for creating tasks intended for parallel execution than an interface,Runnable
much less aThread
. It is worth noting that the ability to add such an interface has appeared only since Java 5, since the key feature of the interfaceCallable
is the use of parameterized types (generics), as shown in the listing.Листинг Creation задачи с помощью интерфейса Callable 10 1 import java.util.concurrent.Callable; 11 2 public class CallableSample implements Callable
{ 12 3 public String call() throws Exception { 13 4 if(Howое-то condition) { 14 5 throw new IOException("error during task processing"); 15 6 } 16 7 System.out.println("task is processing"); 17 8 return "result "; 18 9 } 19 10 } It is immediately necessary to pay attention to line 2, which indicates that the interface
Callable
is parameterized, and its concrete implementation, the classCallableSample
, depends on the typeString
. Line 3 shows the signature of the main method,call
already parameterized, because the type is also specified as the return typeString
. In fact, this means that a task has been created, the result of which will be an object of the typeString
(see line 8). Similarly, you can create a task, as a result of which the methodcall
will create and return an object of any required type. This solution is much more convenient than the interface's run methodRunnable
, which returns nothing (its return type isvoid
) and therefore you have to invent workarounds to extract the result of the task.Another advantage of the interface
Callable
is the ability to "throw" exceptions without affecting other running tasks. Line 3 says that an exception of type can be "thrown" from the methodException
, which actually means any exception, since all exceptions are descendants ofjava.lang.Exception
. Line 5 uses this feature to create a checked exception of typeIOException
.run
The interface methodRunnable
did not allow controlled exceptions to be thrown at all, and the throwing of an uncontrolled (runtime) exception caused the thread and the entire application to stop. -
Is it possible to cancel the execution of a task if the class is used
Future
?Based on this discussion , raised on Habré, it turns out that it is impossible.
There
Future
is a methodFuture.cancel(boolean)
that should cancel the execution of the task. But if the task has already started running, the callFuture.cancel(true)
won't actually stop it. In the bowels of the implementation,FutureTask
the code is executed:if (mayInterruptIfRunning) { Thread r = runner; if (r != null) r.interrupt(); }
Those. again, the thread on which the task is running is only advised to stop executing. In addition, we do not even have the opportunity to know whether the task is currently running or not. There is a method
Future.isDone()
, but again by, it returns true not only when the task has completed execution, but immediately after the callFuture.cancel()
, even if the task is still running (after all,Future.cancel(true)
it does not stop the task that has already started running).Well, if we write all the code ourselves, then we can carefully process it in the right places
Thread.isInterrupted()
and everything will be OK. But what if we run third party code? Should we have a server extensible with plugins? Some crookedly written plugin can easily bring the entire server to an inoperable state, because we cannot correctly interrupt the execution of a hung plugin.
DefNeo
Level 36
GO TO FULL VERSION