JAVA multi-thread and Concurrent learning Summary

Source: Internet
Author: User

JAVA multi-thread and Concurrent learning Summary

1. What is concurrency?
In the operating system, several programs in a period of time are between started and running, and these programs are all running on the same processing machine, however, at any time point, only one program runs on the processing machine.

Note that concurrency and parallelism are two different concepts. Concurrency refers to running at the same time in a time period, which is a interval, while parallelism refers to running at the same time point, which is a point. In addition, concurrency can only be executed by one program at the same time point.

2. What is a process?
In other words, the system opens a process every time an application is opened, such as QQ or storm video. The system allocates resources for the process, such as cpu and memory.

A process is a running activity of a program with independent functions about a data set. It can apply for and possess system resources. It is a dynamic concept and an activity entity. It is not only the code of the program, but also the current activity, expressed by the value of the program counter and the content of the Processing Register.

There are two main concepts of process:First, a process is an entity.Each process has its own address space, generally including text region, data region, and stack region ). The text area stores the code executed by the processor, the data area stores the variables and dynamically allocated memory used during the process execution, and the stack area stores the commands and local variables called during the activity process.Second, the process is a "program in progress ".A program is an inanimate entity. It can become an active entity only when the processor gives it life. We call it a process.

Iii. What is thread
A thread is an entity in a process and the basic unit for independent scheduling and distribution by the system. A thread itself does not own system resources, but only has a point that is essential for running, however, it can share all resources of a process with other threads of the same process.

Generally, a process can contain several threads that can take advantage of the resources of the process. In the operating system that introduces threads, processes are usually used as the basic unit for resource allocation, while threads are used as the basic unit for independent operation and independent scheduling. Because a thread is smaller than a process and basically does not have system resources, the overhead for scheduling is much smaller, it can more efficiently improve the degree of concurrent execution among multiple programs in the system, thus significantly improving the utilization and throughput of system resources. The difference between a thread and a process is that the child process and the parent process have different code and data spaces, while multiple threads share the data space, each thread has its own execution stack and program counter for its execution context. multithreading is mainly used to save CPU time and make full use of it, depending on the specific situation. the computer's memory resources and CPU need to be used during thread running

 
4. What is multithreading technology?
You can think of a running software as a process, just like a large pipeline that does not ship anything, but there are many small pipelines in it, each small pipe is responsible for different things, and these small pipelines can be seen as a thread.

If a single-threaded program is running, and the thread needs to run several functions consecutively, if the running function encounters a waiting or sleep command, he will stop there and do nothing. This is where the CPU is idle and will wait until the program re-runs. If multithreading technology is used, these functions can be run simultaneously (not in the absolute sense). When one function encounters a sleep instruction, other non-sleep functions can continue to run, this can take a shorter time, so that the CPU can be fully utilized to complete the required tasks ~ Threads usually share a code zone, but they have their own independent data storage zones.

V. Summary
CPU is the most valuable resource in the computer. In modern computers, it is often the bottleneck of other hardware, such as slow network I/O and slow memory data reading, which leads to a waste of cpu resources (because the cpu needs to wait ), the proposed multithreading technology solves the difficulty of cpu waiting. When a thread needs to be suspended for other reasons, the cpu can be immediately allocated to other threads.

A single-core cpu system can never implement parallel operations. The cpu can only be asynchronously allocated to the process. Further, it should be a thread. Multi-core CPUs may achieve parallel execution, and two processes run at the same time point. Because the single-thread technology is sequential execution, core resources such as memory and cpu occupy a long time, and the execution efficiency is low, it is a little too slow when the traffic is high and the concurrency is high.

Thread Pool
We recommend that you use the ThreadPoolExecutor factory construction class Executors to manage the thread pool. The thread pool overhead of thread reuse is smaller than that of each new thread application.
Thread Synchronization
Difference between synchronized (this) and synchronized (MyClass. class): the former and the member methods that add synchronized are mutually exclusive, and the latter and the static methods of synchronized are mutually exclusive.

Modifying the get and set methods of variables with synchronized not only ensures the same effect as modifying variables with volatile (get the latest value ), because synchronized not only synchronizes the local copy of the variable modified by the current thread to the primary database, but also reads data from the primary database to update the local copy. Synchronized also has the mutex effect, which can effectively control the concurrent modification of a value, because synchronized ensures the serial execution of the code block. If you only need to obtain the latest value, use volatile, because volatile is lightweight and has good performance.

Mutex lock and read/write lock
ReentrantLock and ReentrantReadWriteLock

JDK5 adds the ReentrantLock class because of two points:

1. reentrantLock provides the tryLock method. When tryLock is called, if the lock is held by another thread (the same thread returns true when calling tryLock twice), tryLock will return immediately, the returned result is false. The lock () method is blocked.

2. Construct a RenntrantLock object to receive a boolean parameter, a function that describes whether the lock is fair or not. The advantage of fair lock is that the thread waiting for the lock will not starve, but the overall efficiency is relatively low. The advantage of unfair lock is that the overall efficiency is relatively higher.
Number of atoms
In addition to the concurrent modification of mutex lock control variables, the atomic class is added to jdk5. the overhead of thread mutex wait is avoided by comparing and exchanging (hardware CAS command, to achieve ultra-lightweight concurrency control, it is generally used to efficiently obtain incremental counters.
Wakeup and notification
Wait, y, and policyall are the three methods on java Object. In multithreading, you can use these methods to complete State notifications between threads.

Y is to wake up a waiting thread, and yyall will wake up all waiting threads.

CountDownLatch mainly provides a mechanism to trigger events when multiple threads (the specific number is equal to the value of the count parameter when the CountDownLatch is initialized) reach the expected state or when the expected work is completed, other threads can wait for this event to trigger subsequent work.
Semaphores
Semaphore is used to manage semaphores. The biggest difference between Semaphore and lock is that the number of tokens can be used to control the number of concurrent threads. When only one semaphores are managed, it degrades to the mutex lock.
Concurrent container
The idea of CopyOnWrite is to write a copy of the container when changing the container to ensure that the reading thread is not affected. It is suitable for scenarios where the application reads more and writes less, because the container is rebuilt once during writing.

Containers starting with Concurrent try to ensure that the read is not locked, and the read is not affected when the modification is made, so it will achieve a higher concurrency performance than using the read/write lock.
**

Java multi-thread interview questions

**

1. What is the difference between processes and threads?

A process is an independent (self contained) running environment, which can be considered as a program or an application. A thread is a task executed in the process. A Java Runtime Environment is a single process that contains different classes and programs. A thread can be called a lightweight process. Threads require less resources to create and reside in the process, and can share resources in the process.

2. What are the benefits of multi-threaded programming?

In multi-threaded programs, multiple threads are concurrently executed to improve program efficiency. The CPU does not enter idle state because a thread needs to wait for resources. Multiple threads share heap memory. Therefore, it is better to create multiple threads to execute some tasks than to create multiple processes. For example, Servlets is better than CGI because Servlets supports multithreading and CGI does not.

3. What is the difference between the user line and the daemon thread?

When we create a thread in a Java program, it is called a user thread. A daemon thread is executed in the background and does not stop JVM termination. When no user thread is running, the JVM closes the program and exits. The sub-thread created by a daemon thread is still a daemon thread.

4. How do we create a thread?

There are two ways to create a Thread: one is to implement the Runnable interface, and then pass it to the Thread constructor to create a Thread object; the other is to directly inherit the Thread class. To learn more, read this article on how to create a thread in Java.

5. What are the different thread lifecycles?

When we create a New thread in a Java program, its status is New. When we call the start () method of the thread, the state is changed to Runnable. The thread scheduler allocates CPU time for the threads in the Runnable thread pool and changes their status to Running. Other thread statuses include Waiting, Blocked, and Dead. Read this article to learn more

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.