Multithreaded programming learning one (the basis of Java multithreading)

1、 Process and thread concepts

Process: the execution of a program is called a process. Each process has independent code and data space. The overhead of switching between processes is relatively large. A process contains 1-N threads. Process is the smallest unit of resource sharing.

Threads: threads of the same type share code and data space. Each thread has an independent running stack and program counter (PC). Thread switching overhead is small. Threads are the smallest unit of CPU scheduling.

Multi process: the operating system can run multiple tasks (programs) at the same time.

Multithreading: multiple sequential streams are executing in the same program. A thread is a single control sequence stream within a process.

2、 Advantages of multithreading

The characteristic of single thread is queue execution, that is, synchronization. Multithreading can maximize the use of CPU idle time to deal with other tasks, and the operation efficiency of the system is greatly improved. Using multithreading is asynchronous execution.

3、 Using multithreading

There are two ways to implement multithreaded programming: one is to inherit the thread class, and the other is to implement the runable interface. In fact, when creating a new thread by inheriting the thread class, the biggest limitation is that it does not support multiple inheritance. Because the Java language is characterized by single root inheritance, in order to support multiple inheritance, the runnable interface can be implemented and inherited at the same time. However, the nature of threads created in these two ways is the same, and there is no essential difference.

This result is demonstrated to illustrate the following two points:

1. The scheduling of threads by CPU is uncertain, so "preemptive" scheduling is adopted.

2. As is often said on the Internet, threads that implement the runnable interface can share data, while threads that inherit threads cannot. In fact, the difference between them is only the limitation of single inheritance and some usage differences (for example, if you want to do something else on this thread object (such as getname), you must call thread The currentthread () method gets a reference to this thread), and there is no substantial difference.

4、 Synchronized keyword

The multi-threaded lock mechanism adds the synchronized keyword in front of the method to be called by the multi-threaded, so that when multiple threads execute the method, they should first try to get the lock. If they can get the lock, the thread can execute the code in synchronize. If you can't get the lock, the thread will keep trying to get the lock until it gets the lock. Synchronized can lock any object or method, and the locked code is called "mutually exclusive area" or "critical area".

The synchronized keyword is mainly used to ensure that the current thread is not preempted by other threads and the shared resources are modified during execution, resulting in thread insecurity.

5、 Common thread methods

1、Thread. Currentthread() method: returns information about which thread the code segment is being called by. The most common is thread currentThread(). getName()。

2. Isalive() method: determines whether the current thread is active. What is active state? The active state is that the thread has been started and not terminated. A thread is considered "alive" when it is running or ready to start running.

3、Thread. Sleep() method: Hibernate (suspend) the executing thread within the specified number of milliseconds. The "executing thread" refers to this The thread returned by currentthread().

4. Getid () method: get the unique ID of the thread.

5、Thread. Interrupt () method: used to interrupt a thread. Note the thread The function of interrupt is not to interrupt the thread, but to "notify the thread that it should be interrupted". Whether to interrupt or continue running should be handled by the notified thread itself. Specifically, when interrupt () is called for a thread,

Interrupt a thread by throwing an exception:

In addition, the thread can be interrupted by retuen's method. However, it is recommended to "throw exceptions" to stop the thread, because exceptions can also be thrown up in the catch block to propagate the event of thread stop.

6、Thread. Yield () method: abandon the current CPU resources and give it to other tasks to occupy CPU execution time. But the time of giving up is uncertain. It is possible to just give up and get the CPU time slice immediately.

7. Setpriority() method: for the portability of the program, Max is recommended_ PRIORITY,NORM_ PRIORITY,MIN_ Priority has three levels. Setting the priority does not mean that the low priority will not be called, but the CPU prefers to let the high priority execute first, but the specific thread called by the CPU cannot be determined. Setting the priority can only ensure that the thread is called more frequently.

8. Setdaemon (true): daemon thread. Daemon thread is a special thread. Its feature has the meaning of "accompany". When there is no non daemon thread in the process, the daemon thread will be destroyed automatically. A typical daemon thread is a garbage collection thread. When there are no non daemon threads in the process, the garbage collection thread is not necessary.

9. Join() method: wait for the thread to terminate. The join () method mainly allows the thread calling the method to complete the things in the run method, and then execute the code behind the join () method. The call to the join () method can be interrupted by calling the interrupt () method on the thread.

6、 Other

1. The stop () method does not guarantee the normal resource release of a thread when terminating a thread. Usually, the thread is not given the opportunity to complete the resource release work, so the program may work in an uncertain state.

2. The suspend () method pauses the thread. The resume () method resumes execution of the thread. When using suspend() and resume(), The thread will not release the resources already occupied (e.g. lock), but occupying resources and entering the sleep state, which is easy to cause deadlock problems. This is a typical example of thread opposition. If two threads hold a thread object at the same time, one attempts to interrupt the thread and the other attempts to recover the thread. If it is carried out concurrently, the target thread will die regardless of whether synchronization is carried out during the call Lock risk.

3. Stop (), suspend (), resume () are discarded due to the reasons mentioned above, and are not recommended.

Daemon thread is a kind of supporting thread, which is mainly used for background scheduling and supporting work in the program. When there is no non daemon thread in the JVM, the Java virtual machine will exit. Therefore, you cannot rely on the finally block of the daemon thread to ensure the logic of closing or cleaning up resources.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>