This is the sixth day of my participation in Gwen Challenge

Multithreading is a broad programming and execution model that allows multiple threads to exist within the context of a process. Each of these threads can run in parallel, and the threads share similar address Spaces. So, let’s start at the beginning.

What is a thread?

The execution of a Thread is the smallest sequence of program instructions that can be managed independently by a scheduler, usually part of the operating system. In most cases, one thread exists in a process, while multiple threads can exist in a single process and are therefore multithreaded.

A programmer sees Thread just as a chemist sees Atom.

These threads run simultaneously and share resources. Threads implementations vary between operating systems and processes, but in most cases threads are part of the process.

What is a process?

Processes are instances of programs that normally run independently of each other. For example, if you start a Java program, the operating system generates a new program thatprocessTo run in parallel with other programs. In these processes, we can execute code concurrently using threads, so we can take full advantage of the CPU’s available kernel.

Unlike threads, processes do not share resources with each other. Process is the unit of resources, and thread is the unit of scheduling and execution.

The thread pool

Creating a brand new OS thread requires memory allocation and CPU instructions to set it up and destroy it. To better handle Thread usage and avoid creating new threads, the operating system or platform considers a Thread Pool feature that allows applications to use existing threads.

This is a more efficient way to process multiple threads without dealing with their creation or destruction. In addition, operating systems know when threads in the thread pool are not actively used, so they can automatically “skip” it during thread iterations.

A descriptive programming representation of threads

We’ll explore thread Runnable implemented from JavaExecutors and two classes in Java.

  • Execute a programExecutorsIs a class of Java that abstracts most manual thread creation. They can run asynchronous tasks and usually manage thread pools, so we don’t have to manually create new threads.

The class Executors provides a convenient factory method to create various execution program services. In the following example, we use an executor with a thread pool of size 1.

The result looks similar to the example above, but when you run the code, you’ll notice one important difference: Java processes never stop! Executors must definitely stop – otherwise they’ll keep listening to new missions.

ExecutorService provides two methods for this purpose: Shutdown () waits for the currently running task to complete, while shutdownNow() interrupts all running tasks and immediately closes the execution program. This service is typically used when socket connections are used to facilitate asynchronous invocation (sink-source connections).

  • Can be run RunnableIs to define a single void parameterless method function interfacerun(). Before starting a new thread, you must specify the code to be executed by this thread, usually called a task, and this is done by implementationRunnable. Note that you can have as many tasks as you want.

For the example above, we print the current thread name to the console using a Java 8 lambda expression. First, we execute runnable directly on the main thread before starting a new thread. See sample output below.

Hello main
Hello Thread-0
Done!
Copy the code

Or this:

Hello main
Done!
Hello Thread-0
Copy the code

We have two possible outputs because, due to concurrent execution, we cannot predict whether runnable will be called before or after printing. The order is uncertain, making concurrent programming a complex task in large applications. Although threads can also be in a certain amount of sleep time.

Deep multithreading

As we stated explicitly earlier, a multi-threaded program consists of two or more parts that can be run concurrently, and each part can handle different tasks simultaneously to make best use of available resources, especially if the computer has multiple cpus.

Multi-threading extends the concept of multitasking to applications where you can subdivide specific operations within a single application into individual threads. It allows you to write a way in which multiple activities can take place simultaneously in the same program.

There are several programming languages that can make room for multi-threading, and most are object-oriented programming languages (OOP). Languages such as Java, C, C++ and even. The.net framework. Other interpreted languages have also made a contribution, such as Ruby MRIforRuby and CPythonfor Python. If you wait to see Javascript, you will not do so because Javascript does not support multithreading, but because the interpreter in the Javascript browser is a single thread.

Lots of multithreaded applications

Almost all well-built applications support multithreading. Let’s take a look at the browser. Most browsers are multithreaded, from Firefox to Safari to Chrome and many more. But today we’re going to talk more about Chrome.

Google Chrome

Chrome has a multi-process architecture, and each process is highly multi-threaded. The main goal is to keep the main thread (the “UI” thread in the browser process) and the IO thread (the thread used for each process that processes IPC) responsive. This means offloading any blocked I/O or other expensive operations to another thread.

In Chrome, each TAB you open has its own content handling. Five tags, five processes, one hundred tags, one hundred processes. This approach maximizes performance, but you pay a heavy price in terms of memory consumption and battery life. Ever wonder why Chrome on Task Manager always uses a lot of CPU? All right, you go.

Every Chrome process has it

  • main threadThis thread updates the UI and runs most Blink.
  • IO threadIPC and network requests for this thread handle
  • There are somespecial-purpose threads
  • A pool ofgeneral-purpose threads

Chrome vs. Firefox

While Chrome creates one content-handling Firefox for each TAB, a maximum of four content-handling threads are rotated by default. In Firefox, the first four tabs use each of these four processes, and the other tabs use threads from those processes. Instead of each TAB creating its own browser, multiple tabs in a process share the browser engine that already exists in memory.

Threads and processes

Threading differs from traditional multitasking in a number of ways:

  • Processes are usually independent, and threads exist as subsets of processes.
  • Processes carry more state information than threads, and multiple threads within a process share process state as well as memory and other resources.
  • Processes have separate address Spaces, and threads share their address Spaces.
  • Processes interact only through the system-provided interprocess communication mechanism.
  • Context switches between threads in the same process usually occur faster than context switches between processes.

parallelism

Parallelism is related to the concept of spreading work across multiple units in a way that does not harm the end product but reduces the total execution time.

Parallel execution is the ability to run two (or more) tasks simultaneously. While concurrency represents possibility, parallelism is a reality.

conclusion

Nowadays, multithreading has become an important part of modern software development. It is supported by many programming languages and platforms and extends all the way to operating systems. Knowing how to use multiple threads can certainly lead developers to build better applications.

More related articles and my contact information I put here: gitee.com/haiyongcsdn…

And finally, don’t forget ❤ or 📑