JavaRush /Java Blog /Random EN /Level 28. Answers to interview questions on the level top...
zor07
Level 31
Санкт-Петербург

Level 28. Answers to interview questions on the level topic

Published in the Random EN group
Hi all! I decided to continue my studies in Javarash, despite the fact that I had already found a job in Java. Level 28. Answers to interview questions on the topic of level - 1I write this blog for myself, very lazily, and, one might say, under pressure. I will be very happy if someone finds it useful, but you should not use it as the main source for finding answers to level questions.

1. What are the thread priorities?

Each thread in the system has its own priority. Priority is some number in the thread object from 1 to 10, with a higher value indicating higher priority. The system executes higher priority threads first, and lower priority threads receive CPU time only when their more privileged counterparts are idle. You can work with thread priorities using two functions:
void setPriority(int priority) //устанавливает приоритет потока.
Possible priority values ​​are MIN_PRIORITY, NORM_PRIORITY and MAX_PRIORITY.
int getPriority() // получает приоритет потока.
Source If priority is not specified, then the thread receives priority 5 - medium. The thread priority does not greatly affect its operation, but is rather advisory in nature. If there are multiple sleeping threads that need to be started, then the Java machine will start the thread with the higher priority first. The Java machine manages the threads as it sees fit. Low priority threads will not be idle. They will simply receive less time than others, but will still be executed. In most cases, threads always run at the same priority. Trying to give one thread more time than others often indicates an architectural error in the program.

2. Is it possible to stop a thread by reducing its priority to 0?

No. Will be thrownIllegalArgumentException

3. Why is the ThreadGroup class needed?

To prevent any thread from stopping and interrupting all threads in a row, the concept of a “group of threads” was introduced. A thread can only affect other threads that are contained in the same group as it. ThreadGroupis a class that manages groups of threads. This approach allows you to protect threads from unwanted changes. Sometimes you have to run code that you can't trust 100%. Therefore, it is convenient to place all its threads in a separate group and prevent them from interfering with the work of the main group of threads. In other words, to manage groups of threads

4. Which group of threads does main-thread belong to?

main

5. What is the ThreadPool pattern

In general terms, a pattern ThreadPoolis a group of threads that solve groups of problems. Tasks are organized into a queue. Once a thread finishes working on a task, it requests the next task from the queue until all tasks in the queue have been completed. After this, the thread can terminate or go to sleep until new tasks appear in the queue.

6. Why do we need the ThreadPoolExecutor class?

To solve a large number of small problems with a group of threads. Using a class avoids wasteful use of machine resources. Because creating your own thread for each task is not very rational. The Java machine allocates quite a lot of resources for each thread. In other words, creating and destroying a spent thread can waste more resources and time than the task itself. Java developers have come up with an elegant solution to this problem - ThreadPoolExecutor. This is a class that has two things inside:
  • A task queue to which you can add tasks as they appear in the program.
  • Pool of threads (group of threads) – which perform these tasks.
In this case, the threads are not destroyed after completing the task, but fall asleep. To start completing a new task as soon as it appears.

7. How many ways to create a thread do you know? (Thread, Runnable, Callable )

public class ThreadsTests {
    //Способ 1
    static class ThreadExampleRunnable implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }

    //Способ 2
    static class ThreadExampleFromThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }

    //Способ 3
    static class ThreadExampleFromCallable implements Callable{
        @Override
        public String call() throws Exception {
            return Thread.currentThread().getName();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new Thread(new ThreadExampleRunnable()).start(); //Способ 1
        new ThreadExampleFromThread().start(); //Способ 2

        //Способ 3
        ExecutorService service = Executors.newFixedThreadPool(5);
        Future task = service.submit(new ThreadExampleFromCallable());
        System.out.println(task.get());

    }
}

8. What is the Future class used for?

This object can be used to find out whether a task has already completed, and also to get the result of its execution. boolean cancel(boolean mayInterrupt); // Останавливает задачу.
boolean isCancelled(); //returns true, если задача была остановлена.
boolean isDone(); //returns true, если выполнение задачи завершено.
V get() throws InterruptedException, ExecutionException; //returns результат вызова метода call or кидает исключение, если оно было.

9. What are the advantages of Callable over Runnable?

Using Callablewe can find out whether the task has completed, and find out its result, much easier than usingRunnable

10. Is it possible to cancel the execution of a task if we use the Future class?

It is possible if the task is in the queue and awaits execution, otherwise not a fact
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION