JavaRush /Java Blog /Random EN /Multithreading in Java
Author
Pavlo Plynko
Java-разработчик at CodeGym

Multithreading in Java

Published in the Random EN group

Introduction

Before learning about Java threads, let's look into the near future. Imagine you submitted your resume and had an interview. You and a couple of dozen future colleagues have been invited to work at a large Software company. Among other hassles, you need to submit paper documents for employment to a tired HR employee.
Multithreading in Java - 1
To speed up the process, applicants for the position can be divided into two groups and distributed between two HR managers (if there are any in the company). As a result, we speed up the process due to parallel design work.
Multithreading in Java - 2
If there is only one personnel officer in the company, then you will have to somehow get out. For example, you can again divide everyone into two groups, for example, interview girls and boys in turn.
Multithreading in Java - 3
Or according to another principle: since there are more people in the lower group, we will alternate two girls for one boy.
Multithreading in Java - 4
This way of organizing work is called multi-threaded . Our tired HR officer switches to different groups to recruit the next employee from them. There are maybe eleven groups, and four personnel officers. In this case, multithreading processing will occur in parallel by several HRs, who can take the next person from any group to process his documents.

Processes

The process ( process ) in this case will be the organization of document reception work. In an organization, several processes can be distinguished: accounting, software development, meetings with clients, warehouse operations, etc. Resources are allocated for each process: premises, employees for its execution. The processes are isolated from each other: HR officers do not have access to the accounting database, and customer service managers do not run around the warehouse. If a process needs to gain access to someone else's resources, it is necessary to establish inter-process communication: memos, joint meetings.

Streams

Work in a process is organized into threads ( java thread). For the HR department, flow is the organization of work to serve a group. In the very first picture there is one flow, in the next three there are two. Within the process, threads can be executed in parallel - two HR officers accept two or more groups of future employees. The interaction of personnel officers with groups - the processing of threads within a process - is called thread synchronization . The drawings of the design of two groups by one personnel officer show methods: uniform (girl - boy - girl - boy) and with different priorities (two girls alternate with one boy). Threads have access to the resources of the process to which they belong: groups to the HR officer are given samples of application forms, pens for filling out documents. But if flows interact with things common to them, then incidents are possible. If the personnel officer asks you to shout the name of the last person in the queue, then, in the case of two groups, he is not sure in advance whether he will hear a woman’s name or a man’s. Such data access conflicts, blocking and ways to resolve them are a very important topic.

Flow states

Each thread is in one of the following states:
  • Created ( New) – the line for the HR officer is getting ready, people are getting organized.
  • Launched ( Runnable) – our queue has lined up for the HR officer and is being processed.
  • Blocked ( Blocked) – the last guy in the queue tries to shout out a name, but when he heard that the girl in the next group started doing it before him, he fell silent.
  • Completed ( Terminated) - the entire queue has been completed by the HR officer and there is no need for it.
  • Waiting( Waiting) – one queue is waiting for a signal from another.
The organization of threads and their interaction is the basis for the effective operation of processes.

Let's return to the IT world

In the 21st century, multi-threaded and parallel execution has become relevant. Since the 90s of the last century, multitasking operating systems Windows, MacOS and Linux have become firmly established on home computers. You can often find four or more core processors in them. The number of parallel blocks of GPU video cards has already exceeded a thousand. Popular programs are written taking into account multithreading (multithreading), for example, modern versions of software for processing graphics, video, or operating with large amounts of data: Adobe Photoshop, WinRar, Mathematica, modern games. Java multithreading is a very important, popular and complex topic. Therefore, in the JavaRush course there are many tasks to understand it very well. Java examples on multithreading will help you master the basic nuances and subtleties of this area, synchronizing the work of threads.

Process

Process is a running instance of a program to which the Operating System (OS) has allocated memory, processor time/cores, and other resources. It is important that memory is allocated separately; the address spaces of different processes are not accessible to each other. If processes need to communicate, they can do so using files, pipes, and other interprocess communication methods.

Flow

Java Thread(stream). Sometimes, to avoid confusion with other Java classes Streamand the like, Java threads are often translated as a thread. They use the resources allocated to a process and are the way the process is executed. The main thread executes the method mainand exits. When a process executes, additional threads (child threads) can be spawned. Threads of the same process can exchange data with each other. Java multithreading requires data synchronization to be taken into account, don't forget about it. In Java, a process terminates when its last thread has finished. For background tasks, a thread can be started as a daemon ( daemon), the difference from a regular one is that they will be forcibly terminated when all non- daemonthreads of the process terminate.

First multi-threaded application

There are more than half a dozen ways to create threads; in the JavaRush course we will examine them in detail. First, let's get acquainted with one of the basic ones. There is a special class Threadin the method run()of which you need to write code that implements the logic of the program. After creating a thread, you can start it by calling the start(). Let's write a demo program that implements an example of Java multithreading.
class PeopleQueue extends Thread    {// Наша очередь из сотрудников, наследник класса Thread
    private String[] names;

    PeopleQueue(String... names) {// Конструктор, аргумент- массив имен сотрудников
        this.names = names;
    }

    @Override
    public void run() { // Этот метод будет вызван при старте потока
        for (int i = 0; i < names.length; i++) { // Вывод в цикле с паузой 0.5 сек очередного сотрудника
            System.out.println("Обработаны documentы: " + names[i]);
            try {
                sleep(500); // Задержка в 0.5 сек
            } catch (Exception e) {}
        }
    }
}

public class HR    {// Класс для демонстрации работы потока
    public static void main(String[] args) {
        // Создаем две очереди
        PeopleQueue queue1 = new PeopleQueue("Ivan","Сергей","Николай","Фердинанд","Basil");
        PeopleQueue queue2 = new PeopleQueue("Мария","Людмила","Алиса","Карина","Olga");

        System.out.println("Начали!"); // Сообщение из главного потока программы
        queue1.start();    //Запускаем одну очередь (дочерний поток)
        queue2.start(); //Запускаем вторую (дочерний поток)
    }
}
Let's launch the program. The console displays the message output from the main thread. Next, each child thread queue1in queue2turn outputs messages to their common console about the next processed employee. One of the possible options for the program:
Начали!
Обработаны documentы: Мария
Обработаны documentы: Ivan
Обработаны documentы: Людмила
Обработаны documentы: Сергей
Обработаны documentы: Алиса
Обработаны documentы: Николай
Обработаны documentы: Карина
Обработаны documentы: Фердинанд
Обработаны documentы: Ольга
Обработаны documentы: Васorй

Process finished with exit code 0
Multithreading in Java is a complex and multifaceted topic. The ability to write code using parallel, multitasking and multithreaded computing will help you effectively implement tasks on modern multi-core processors and clusters consisting of many computers.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION