Java multithreading mechanism

Source: Internet
Author: User

1. threads in Java

1.1 programs, processes, and threads

A program is a piece of static code, which is the blueprint for application software execution.

A process is a dynamic execution process of a program. It corresponds to a complete process from code loading, execution to execution completion. This process is also a process from process generation, development to extinction.

A thread is a smaller execution unit than a process. A process can generate multiple threads during execution to form multiple execution clues. Each thread also has its own production, existence, and extinction processes, it is also a dynamic concept.

1.2 thread status and lifecycle

Java uses the Thread class and its subclass objects to represent the thread. The newly created thread usually goes through the following four States in a complete lifecycle.

L new

When a Thread class or its subclass object is declared and created, the new thread object is in the new State. Now it has the corresponding memory space and other resources.

L run

After a thread is created, it meets the running conditions. Once it is its turn to enjoy CPU resources, that is, when the JVM switches the CPU usage right to this thread, this thread can start its own life cycle independently from the main thread that created it.

L interrupt

L death

1.3 Thread Scheduling and priority

2. Thread class subclass creation thread

3. Use the runnable interface

The advantage of using the thread subclass to create a thread is that a new member variable can be added to the subclass so that the thread has a certain attribute. You can also add a method to the subclass to make the thread have a certain function. However, Java does not support multi-inheritance, and the subclass of the thread class cannot expand other classes.

1) runnable interface and target object

Another way to create a thread is to use the Thread class to directly create a thread object. When using thread to create a thread object, the following constructor is usually used:

Thread (runnabletarget)

The parameter in this constructor is a runnable interface. Therefore, when creating a thread object, you must pass an instance that implements the runnable interface class to the constructor, this instance object is called the target object of the created thread. When the thread calls the START () method, once it is its turn to enjoy CPU resources, the target object will automatically call the run () method (interface callback), which is automatically implemented. The user program only needs to let the thread call the start () method, that is, when the thread is scheduled and transferred to the running status, the operation is the operation specified in the run () method.

2) about local variables in the run () method

For threads with the same target object, when one of the threads consumes CPU resources, the target object automatically calls the run () method in the interface. In this case, run () the local variables in the method are allocated memory space. When it is another thread's turn to use CPU resources, the target object will call the run () method in the interface again. Then, run () the local variables in the method will allocate memory space again. That is to say, the run () method has been started and run twice in different threads, that is, it runs in different time slices. Local variables in the run () method of different threads do not interfere with each other. A thread changes the value of local variables in its run () method and does not affect the run () of other threads () the value of the local variable in the method.

3) Start other threads in the thread

The thread starts the thread by calling the START () method, so that it enters the ready queue from the new state. Once it is its turn to enjoy CPU resources, you can start your own life cycle independently from the main thread that created it.

4. common thread Methods

1) Start () method

When a thread calls this method, it starts the thread and enters the ready queue from the new state. Once it is its turn to enjoy CPU resources, you can start your own life cycle independently from the thread that created it.

2) Run () method

The run () method of the thread class has the same functions and functions as the run () method in the runnable () interface, and is used to define the operations executed after the thread object is scheduled, these methods are automatically called by the system and cannot be referenced by user programs. In the Thread class of the system, the run () method has no specific content. Therefore, the user program needs to create its own subclass of the thread class, and rewrite the run () method to overwrite the original run () method () method. When the run () method is executed, the thread becomes dead. The so-called dead State means that the thread releases the entity, that is, the memory allocated to the thread object. Before the thread ends the run () method, the thread is not allowed to call the START () method again. Otherwise, the illegalthreadstateexception will occur.

3) sleep (INT millsecond) Method

If the thread is interrupted during sleep, the JVM throws an interruptedexception exception. Therefore ~ Call the sleep method in the catch statement block.

4) isalive () method

When the thread is in the "new" status, the thread calls the isalive () method and returns false. When a thread calls the START () method and occupies CPU resources, the run () method of the thread starts to run. Before the run () method of the thread ends, that is, the thread calls the isalive () method to return true before it enters the dead state. When the thread enters the "dead" State (the physical memory is released), the thread can still call the isalive () method, and the returned value is false.

5) currentthread () method

This method returns the thread that is currently using CPU resources.

6) interrupt () method

This method is used to "wake up" the thread. When some threads call the sleep method in sleep state, a thread occupying CPU resources can make the sleeping thread call the interrupt method to "wake up" itself, which leads to an interruptedexception exception in the sleeping thread, this ends sleep and waits for CPU resources again.

5. Gui thread

When a Java program contains a graphical user interface (GUI), the Java Virtual Machine (JVM) automatically starts more threads when running the application. There are two important threads: AWT-eventquecue and AWT-Windows. The AWT-eventquecue thread is responsible for processing GUI events, and the AWT-windows thread is responsible for drawing forms or components to the desktop. JVM should ensure that each thread has the opportunity to use CPU resources. When the window needs to be refreshed, JVM will switch the CPU resources to the AWT-windows thread; when a GUI event occurs in the program, the JVM switches the CPU resource to the AWT-eventquecue thread, and the AWT-eventquecue thread processes the event.

6. Thread Synchronization

When processing thread synchronization, the first thing to do is to modify the data modification method with the keyword synchronized. After a method is modified with the keyword synchronized, when thread a uses this method, other threads must wait until thread a uses this method. The so-called thread synchronization means that several threads must use a synchronized modifier.

7. Use the wait (), Policy (), and policyall () methods in the synchronization method.

When a variable is used in the synchronization method used by a thread and needs to be modified by another thread to meet the needs of the thread, you can use the wait () method in the synchronization method. You can use the wait () method to interrupt the execution of the method, so that this thread can wait, temporarily give up the CPU usage right, and allow other threads to use this synchronization method. If other threads do not need to wait when using this synchronization method, they should use policyall () when using this synchronization method () method to notify all threads that are waiting for the synchronization method to end and wait. The thread that has been interrupted will continue to execute this synchronization method from the interrupt and follow the principle of "first interrupt first. If the notify () method is used, only one end wait of the thread in the waiting state is notified.

Wait (), Policy (), and policyall () are all final methods in the object class. They are inherited by all classes and cannot be overwritten.

8. Thread suspension, recovery, and Termination

Sometimes the two threads are not synchronous, that is, they do not need to call a synchronous method, but the thread may need to be temporarily suspended. The so-called suspension of a thread is to temporarily let the thread out of the CPU usage permission, stop the execution, but the duration of the stop is unknown, so the sleep method cannot be used to suspend the thread. To suspend a thread, you need to use the wait () method, that is, let the thread preparing for suspension call the wait () method, take the initiative to give the CPU usage permission, and temporarily stop the execution. The so-called recovery thread is to let the suspended thread resume the execution process, that is, to continue the thread execution from the disconnection. In order to restore this thread, when other threads occupy CPU resources, execute the yyall () method on the target object of the suspended thread so that the suspended thread can continue to execute. If the thread does not have a target object, to recover this thread, when other threads occupy CPU resources, let the suspended thread call the yyall () method, so that the suspended thread can continue to execute. To terminate a thread, the thread stops running the run () method and enters the dead state.

9. Timer thread Timer

10. Thread Union

When a thread a occupies CPU resources, other thread B can call join () and join the thread. If thread a associates with thread B when it occupies CPU resources, thread a will immediately interrupt the execution and wait until the thread B that it joins completes the execution. Thread a then queues again to wait for CPU resources, to resume execution. If thread a is ready to join thread B, thread combination will not produce any effect.

11. daemon thread

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.