Java multithreading and java multithreading instances
Windows and other operating systems support concurrent processing of multi-threaded processes. The operating system supports multiple threads, enabling concurrent execution of multiple programs to improve resource usage and system efficiency. The operating system supports multiple threads, which can reduce the time and space overhead of concurrent programs, this improves the development granularity and concurrency.
Process
A process is an execution process of a program on a data set. It is the basic unit for the operating system to allocate and protect resources. A process has the following features:
① Structured. Processes contain programs that combine datasets and run on them. Each process consists of at least three elements: program block, data block, and process control block. Process Control blocks (PCB) describe and record the dynamic Process of processes so that processes can run correctly.
② Independence. Processes are not only the basic unit for resource allocation and protection in the system, but also an independent unit for System Scheduling (single-threaded processes). Each process runs at its own speed on the CPU.
③ Dynamic. A process is an execution process of a program on a dataset. It is a dynamic concept. Its lifecycle changes among multiple states, generated by creation, executed by scheduling, blocked by waiting conditions, and extinct by cancellation. A program is a set of ordered command sequences. It is a static concept. As a system resource, a program permanently exists.
④ Concurrency. The concurrency of a process means that the execution of a group of processes overlaps in time.
⑤ Interaction. Multiple processes can share variables and communicate with each other through shared variables. Multiple processes can collaborate to complete a task.
Thread
A thread is an entity (control flow) that can be executed independently in a process. It is the basic unit for Processor Scheduling and allocation. A thread is a component of a process. Each process can contain multiple concurrent threads. All threads in the same process share the memory space and resources obtained by the process, but do not own resources.
Multi-threaded processes are supported.
The main features of a thread are as follows:
① Structured. A thread is the basic unit for Operating System Scheduling. It has a unique identifier that complies with the thread control block and contains all the information required for scheduling.
② Dynamic. The thread is dynamic and has state changes. When a process is created, at least one thread is created for it, and other threads are created as needed. Terminating a process will terminate all threads in the process.
③ Concurrency. Multiple Threads of a process can be concurrently or concurrently executed on one or more processors. Concurrent execution between processes evolves to concurrent execution between threads. On a single processor, from a macro perspective, several threads are running in a single time period. On the micro level, only one thread runs on the processor at any time. The essence of concurrency is the multiplexing of a processor among multiple threads. It forces Multi-User Sharing of limited physical resources to eliminate mutual phenomena between computers and improve the utilization of system resources.
④ Sharing. All threads of the same process share the state and resources of the process and reside in the memory space of the process. The same data can be accessed. Communication and synchronization mechanisms are required between all threads.
Thread status
A thread changes its state in its lifecycle. There are five types of thread states: new, ready, running, blocking, and terminated.
Ready (ready) State-the process has running conditions, waiting for the system to allocate a processor for running.
Running State: the processor is running.
Blocked state: the process does not meet the running conditions and is waiting for the completion of an event.
A thread is in one State at any time in the execution process and changes between multiple States according to the running conditions. After a process is created, it is in the ready state and running is in the blocking state due to the waiting condition.
Thread Scheduling
At any time, only one thread can occupy one processor for running. The principle determines which thread in the ready queue can obtain the processor as a task scheduled by the thread.
The function of thread scheduling is to select a thread according to certain principles so that it can run on a processor. Thread Scheduling is the core part of the operating system. The advantages and disadvantages of Thread Scheduling Policies directly affect the performance of the operating system.
Thread Scheduling adopts the deprivation mode. When a thread is being executed on the processor, the operating system can deprive it of the right to use the processor according to the prescribed principles, and allocate the processor to other threads for use. There are two common deprivation principles: one is that high-priority threads can deprive low-priority threads of running, and the other is the pineapple processor after the running thread time is used up.
Concurrent Program Design
The sequential program design method refers to the execution of program modules in the order of statements. The features are: ① execution sequence; ② closed runtime environment; ③ execution result certainty; ④ calculate the reproducibility of the dismissal couple.
The concurrent program design method refers to dividing a program into several program modules that can be executed at the same time. Each program module is combined with the data processed during its execution to form a process. The operating system uses processes as the basic unit for system resource allocation and the basic unit for thread system scheduling. Its features are as follows:
① Threads for concurrent execution are not sequential. The thread is scheduled by the operating system and not executed in the order of statement writing.
② The runtime environment is no longer closed. The execution of one thread may affect the execution results of other threads. (The computing process cannot be reproduced)
③ Multiple threads that share variables (become interactive threads) Implement thread communication. When a task can be completed collaboratively, errors related to time may also occur.
④ The advantage of concurrent multi-threaded programming is that it improves the system performance, specifically for fast thread switching, reducing system management overhead, making thread communication easy to implement, increasing concurrency by program, and saving memory space.
Java thread object
Java supports the built-in multithreading mechanism. The Runnable interface in the Java language Package specifies the Thread execution method. The Thread class provides methods for creating, managing, and controlling Thread objects.
In java, You can implement multithreading in two ways. One is to inherit the Thread class, the other is to implement the Runnable interface, and the Thread class is defined in the java. lang package. As long as a class inherits the Thread class and overwrites the run () method in this class, it can implement multi-threaded operations. However, a class can only inherit one parent class, which is the limitation of this method.
public class NumberThread extends Thread{ private int first; public NumberThread(String name, int first){ super(name); this.first = first; } public void run(){ System.out.print(this.getName() + ":"); for (int i = first; i < 100; i += 2){ System.out.print(i + " "); } System.out.println(this.getName() + "End!\n"); } public static void main(String[] args){ System.out.println("Current Thread:" +Thread.currentThread().getName()); NumberThread thread1 = new NumberThread("JISHU", 1); NumberThread thread2 = new NumberThread("OUSHU", 2); thread1.start(); thread2.start(); System.out.println("Active Count:" + Thread.activeCount()); }}
In the installation environment of JDK, src.zip is the full java source program. By finding the definition of the start () method in Thread, we can find that private native void start0 () is used in this method (); the native keyword indicates that the underlying functions of the operating system can be called, so this technology becomes JNI technology (java Native Interface ).
In actual development, a multi-threaded operation rarely uses the Thread class, but is completed through the Runnable interface. However, the start () method is not available in the subclass defined by Runnable, and is available only in the Thread class. Observe the Thread class, there is a constructor: public Thread (Runnable targer) This constructor accepts Runnable subclass instances, that is, you can use the Thread class to start the multi-Thread implemented by Runnable. (Start () can coordinate system resources)
public class NumberRunnable implements Runnable{ private int first; public NumberRunnable(int first){ this.first = first; } public void run(){ for (int i = first; i < 50; i += 2){ System.out.print(i + " "); } System.out.println("End!\n"); } public static void main(String[] args){ NumberRunnable target = new NumberRunnable(1); Thread thread1 = new Thread(target, "JISHU"); thread1.start(); new Thread(new NumberRunnable(2), "OUSHU").start(); }}
Differences and links between the two implementation methods:
In program development, as long as it is multi-Thread, it will always be dominated by implementing the Runnable interface, because implementing the Runnable interface has the following advantages over inheriting the Thread class:
① Suitable for multiple threads with the same program code to process the same resource (suitable for Resource Sharing)
② Avoid the limitation of single inheritance in java
③ Increase program robustness. The code can be shared by multiple threads, and the code and data are independent.
Use a ticket program to illustrate the differences between the two methods:
Inherit Thread class:
Public class TicketThread extends Thread {private int count = 10; public TicketThread (String name) {super (name);} public void run () {while (count> 0) {System. out. println (Thread. currentThread (). getName () + "is selling ticket:" + count); count -- ;}} public static void main (String [] args) {TicketThread thread1 = new TicketThread ("Window 1"); TicketThread thread2 = new TicketThread ("window 2"); thread1.start (); thread2.start ();}}
Output result:
Window 2 is selling ticket: 10 window 2 is selling ticket: 9 window 2 is selling ticket: 8 window 2 is selling ticket: 7 window 2 is selling ticket: 6 window 2 is selling ticket: 5 window 2 is selling ticket: 4 window 2 is selling ticket: 3 window 2 is selling ticket: 2 window 2 is selling ticket: 1 window 1 is selling ticket: 10 window 1 is selling ticket: 9 window 1 is selling ticket: 8 window 1 is selling ticket: 7 window 1 is selling ticket: 6 window 1 is selling ticket: 5 window 1 is selling ticket: 4 window 1 is selling ticket: 3 window 1 is selling ticket: 2 window 1 is selling ticket: 1
Implement the Runnable interface:
Public class TicketRunnable implements Runnable {private int count = 10; public void run () {while (count> 0) {System. out. println (Thread. currentThread (). getName () + "is selling ticket:" + count --) ;}} public static void main (String [] args) {TicketRunnable target = new TicketRunnable (); new Thread (target, "Window 1 "). start (); new Thread (target, "window 2 "). start ();}}
Output result:
Window 1 is selling ticket: 9 window 1 is selling ticket: 8 window 1 is selling ticket: 7 window 1 is selling ticket: 6 window 1 is selling ticket: 5 window 1 is selling ticket: 4 window 1 is selling ticket: 3 window 1 is selling ticket: 2 window 1 is selling ticket: 1 window 2 is selling ticket: 10
If you execute the program multiple times, you can find that the above program may sell the ticket numbered 0. This involves the thread synchronization mechanism, which will be mentioned in subsequent articles.
Thread object priority
Java provides 10 levels of thread priority, with 1 ~ 10 indicates that the minimum priority is 1, the maximum is 10, and the default value is 5. The Thread class declares the following three public static constants that indicate priority:
Public static final int MIN_PRIORITY = 1; // minimum priority
Public static final int MAX_PRIORITY = 2; // highest priority
Public static final int NORM_PRIORITY = 3; // default priority
Each thread automatically obtains the default priority 5 when it is created. Calling the setPriority () method can change the priority of the thread object.
Thread object Lifecycle
Six thread states:
① New state (NEW). Created, not started.
② Running state (RUNNABLE). From the operating system perspective, after a thread in the new State is started, it enters the ready state, and then scheduled and executed by the operating system to become the running state. Because thread scheduling is controlled and managed by the operating system, the program cannot be controlled and the ready state and running state cannot be distinguished. Therefore, from the perspective of program design, after the thread is started, it enters the running state RUNNABLE. The thread that enters the running state executes its run () method.
③ Blocking state (BLOCKED) And wait state. When a running thread is not running for some reason, it enters the blocking or waiting state. There are two waiting states:WAITING(The waiting time is uncertain) andTIMED_WAITING(Wait for the time to confirm ).
④ Termination state (TERMINATED). When the thread object stops running and is not canceled, it is terminated.
How to change and determine the Thread status in the Thread class:
- Start () creates a state to the running state.
- IsAlive () determines whether the thread is active. Returns true if a thread is not terminated. The thread is in the running, blocking, and waiting state. If a thread is not started or terminated, false is returned.
- The sleep () method stops the execution of the current process for several milliseconds. The thread waits for the State from the running state to the sleep time, And the thread can run the state again.
- The interrupt () method sets an interrupt mark for the current thread so that IsInterrupted () can be detected when the run () method is running. In this case, when a method like sleep () is blocked, the sleep () method throws java. lang. InterruptedException and the thread interruption exception. This exception can be caught for interrupt processing.
Interrupt () only sets an interrupt mark for the thread and does not interrupt the thread running. This method does not throw an exception. A thread can still run after being configured with the interrupt mark, and isAlive () returns true.
When an InterruptedException exception is thrown, the mark that records the thread interruption will be cleared, and then calling isInterrupted () will return false.
Thread Synchronization Mechanism
There are two relationships between interactive threads:Competitive relationshipAndCollaboration.
UseThread mutexTo solve the shared resource conflicts.Thread SynchronizationSolve the problem of inter-thread communication and non-synchronization caused by inconsistent execution speed.
The concurrent threads of interaction mean that they share certain variables. The execution of one thread may affect the execution results of other threads, and the concurrent threads of interaction have a restricted relationship.
No time-related errors will occur during concurrent execution between unrelated threads.
There are two problems in resource competition: one isDeadlock(Deadlock) Problem, if a group of threads get some resources and want to get the resources occupied by other threads, all the threads will eventually be deadlocked; the other isHunger(Starvation) Problem, a thread is delayed indefinitely because other threads always give priority to it.
Thread mutex and critical zone management
Thread mutex is a means to solve the competition between threads.Thread mutex(Mutual exclusion) means that when several threads want to use the same shared resource, a maximum of one thread can be used at any time. Other threads that want to use the resource must wait, wait until the thread that occupies the resource releases the resource.
The shared variable indicates that the resource becomesCritical resources(Critical resource), the program segment in the concurrent thread related to the shared variable becomesCritical Section(Critical section ). The critical section related to the same variable is scattered in the program segments of related threads, and the execution speed of each thread is unpredictable. Therefore,The operating system has the following three scheduling principles for several threads that share a variable entering the critical section.:
① At most one thread can be in its critical section at a time
② A thread cannot stay in its critical section indefinitely
③ A thread cannot be forced to enter its critical section infinitely. In particular, any thread entering the critical section cannot impede the progress of other threads waiting to enter.
The Scheduling Principle of the critical section is summarized into four sentences: no blank wait, free let in, choose one and choose, and the algorithm is feasible.
The operating system provides a mutex mechanism to allow concurrent threads to access the critical section and operate on shared resources.
Java mutex implementation
Keywords provided by JavaSynchronizedIt is used to declare a program as a critical zone, so that the thread uses mutex for critical resources. Synchronized can be used to declare a statement or a method.
①Synchronous statement
Synchronized (object)
Statement
Among them, the object is a public variable that multiple threads operate together, that is, the critical resource to be locked.
②Synchronization Method
Synchronized Method Declaration
The method body of the synchronous method becomes a critical section. The object that calls this method is mutually exclusive (locked.
Collaboration between threads and thread synchronization
When one of the partner threads reaches the coordination point, they should block themselves before receiving a signal from their partner threads until other partners send a coordination signal before being awakened and executed. The Coordination Relationship Between the cooperative threads waiting for messages or signals from each other becomes thread synchronization.
Thread Synchronization is a means to solve the cooperative relationship between threads. Synchronization refers to two or more threads coordinating their activities based on a certain condition. The execution of one thread depends on the signal of another thread. When a thread does not receive the signal from another thread, it needs to wait until the signal arrives before it is awakened.
Thread mutex is a special thread synchronization mechanism, that is, the successive use of mutex to share resources is also a coordination of the resource order used by threads.
One way to achieve thread synchronization in the operating system isSemaphoresAndPV operation. The operation to test the semaphore State becomes a P operation. The operation to change the semaphore state is called a V operation. These two operations are mutually exclusive and cannot be interrupted during execution. Multiple Threads determine each other based on the semaphore status.
Java thread Communication Method
The java. lang. Object class provides the wait (), Y (), and notifyAll () methods for inter-thread communication.
Note:
- No matter whether the synchronized keyword is applied to methods or objects, the lock it acquires is an object, instead of using a piece of code or function as a lock-and the synchronization method may be accessed by objects in other threads.
- Each object has only one lock associated with it.
- Implementing synchronization requires a large amount of system overhead as a cost, and may even cause deadlocks. Therefore, avoid unnecessary synchronization control as much as possible.
When synchronized is used as the function modifier, it locks the synchronous method object. That is to say, when an object P1 executes this synchronization method in different threads, they are mutually exclusive to achieve synchronization. However, the other object P2 generated by the Class to which this object belongs can call the method with the synchronized keyword.