Java basics 008-Multithreading

Source: Internet
Author: User

Java basics 008-Multithreading

Learning Java at the age of 35

1. Concepts of processes and threads. 1) conceptual process: a program in progress (literally translated). Thread: a control unit (Execution path) task in the process that is responsible for program execution: Each thread has its own running content. This content can be called a task to be executed by a thread. Tip: Multiple execution paths can be called multithreading in a process. A process must have at least one thread. 2) The purpose of creating multithreading is to enable multiple threads to run multiple pieces of code at the same time. 3) The principle of multithreading in fact, the execution of applications is completed by a fast switch of the CPU. This switch is random. 4) Advantages and Disadvantages of multithreading multi-threading: solves the problem of Running multiple parts simultaneously. Multithreading disadvantages: too many threads lead to lower efficiency. 5) When JVM is started, multiple threads are started to execute the main function. The task code of this thread is defined in the main function. Garbage collection thread. Custom thread 2. Thread creation method 1 inherits Thread class 1) The subclass overwrites the run method in the parent class and stores the code running the thread in the run. 2) The thread is also created when a subclass object is created. 3) Enable the thread by calling the start method. Four States of a thread

 

3. Thread creation method 2) Implement the runnable interface subclass to overwrite the run method in the interface. 2) create a thread through the Thread class and pass the subclass object that implements the runnable interface to the constructor of the thread class as a parameter. The thread Class Object calls the start method to enable the thread. 3) thinking: why should we pass the runnable subclass object to the constructor of the thread class? Because all the tasks of the thread are encapsulated in the run method of the runnable interface subclass object. Therefore, when creating a thread object, you must specify the task to be run. 4) benefits of implementing the runnable interface: A. Separate a thread task from its subclass and encapsulate it separately. Encapsulate tasks into objects according to object-oriented thinking. B. Avoiding the limitations of Java single inheritance.

 

4. Causes of security problems caused by thread security issues: 1) Multiple Threads operate on shared data. 2) There are multiple thread codes that operate on shared data. 3) random threads. When a thread is executing multiple codes that share data, other threads are involved in the operation. This will cause thread security issues. Note: in ideal conditions, thread security problems are not easy to occur, but the impact on software is very large once they occur.

5. The idea of synchronized to solve the thread security problem is to encapsulate the thread code that shares data among multiple operations. When a thread is executing the code, other threads cannot participate in operations. Only when the current thread finishes executing the code can other threads participate in the operation.

 

Format: synchronized (object) {code to be synchronized;} the root cause of the security problem is the object. This object is like a lock function. 5.1 prerequisites for synchronization: 1) Synchronization requires two or more threads. 2) Multiple Threads use the same lock. The two conditions are not met and cannot be called synchronization. 5.2 disadvantages of synchronization: when there are quite a few threads, every thread will judge the lock on synchronization, which is very resource-consuming and will virtually reduce the running efficiency of the program. 5.3 synchronous Function Format: add the synchronized modifier to the function. Think: Which lock is used for Synchronous functions? (This)

 

6. Inter-thread Communication

 

6.1 wait/wake-up mechanism. 1) Wait (): puts the thread in the frozen state, and the thread that is wait will be stored in the thread pool. 2) y (): Wake up one thread (any) in the thread pool. Only one thread can be awakened. It makes no sense if the local thread wakes up the local thread. Besides, the while flag + policy will cause a deadlock. 3) yyall (): Wake up all threads in the thread pool. Solved the problem that the local thread will wake up the other thread. These methods must be defined in synchronization. These methods are used to operate the thread status. 6.2 New Mechanism 1) JDK encapsulates synchronization and lock into objects. The operation lock is implicitly defined in this object, and the implicit action is changed to the display action. 2) Lock interface: the synchronization code block or function is replaced. Change the synchronous implicit Lock operation to an explicit Lock operation. At the same time, it is more flexible. Multiple sets of monitors can be added to one lock. Lock (): Get the lock. Unlock (): Release the lock, which usually needs to be defined in the finally code block. 3) condition interface: Replace the wait, policy, and policyall methods in the object. These monitor methods are encapsulated separately and become the condition monitor object. Any lock can be combined. Await (); signal (); signalall ();

 

7. Stop thread 1) define the loop end mark because the Running code of the thread is usually a loop, as long as the loop is controlled. 2) use the interrupt (Interrupt) method. This method stops the thread freezing and returns the thread to the running state. The force action will cause interruptedexception. Remember to handle it. Note: The stop method is no longer used when it is out of date.

 

8. Other methods of the thread Class 1) After setpriority (INT num) is set, the chance of obtaining CPU execution right can be changed. The higher the priority, the higher the chance of obtaining CPU execution right. The default value is 5 (norm_priority), the minimum value is 1 (min_priority), and the maximum value is 10 (max_priority), which is a static constant. 2) setdaemon (Boolean B) sets this thread as a daemon (background thread). When all running daemon threads are running, the virtual machine exits. This method must be called before the thread is started. 3) join () can be used to temporarily Add a thread operation. This thread will obtain the execution qualification and execution right. 4) tostring () returns the string representation of the thread, including the name, priority, and thread group (the thread group can unify the threads in the management group, such as interrupt .) 5) yield (); pause the currently executing thread object and execute other threads. Is a static method.
Related Article

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.