I. Multithreading
1.1 process
Threads are process-dependent. Process: is a running program
-
A separate unit of resource allocation and invocation by each system
-
Each process has its own memory space and system resources
1.2 the thread
Thread: is a single sequential control flow in a process, a path of execution
- Single thread: There is only one execution path
- Multithreading: There are multiple execution paths
1.3 Implementation of multithreading
Java.lang Public class Thread -> Extends Object implements Runnable Java virtual machine allows an application to execute multiple threads at the same time.
Method 1: Define a class that inherits Thread and override the Run method of Thread.
public class MyThread extends Thread{
@Override
public void run(a) {
super.run();
for(int i = 0; i <100; i++) { System.out.println(i); }}}Copy the code
public static void main(String[] args) {
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
// The run method does not start the thread
// my1.run();
// my2.run();
//viod start() causes the thread to start executing; The Java virtual machine calls the run method of this thread
my1.start();
my2.start();
}
Copy the code
Question 1: Why override the run method? Because run() is code that encapsulates thread execution. Run () : encapsulates the code executed by the thread, called directly, equivalent to ordinary method call start() : starts the thread; The VM then calls the run() method of this thread
Method 2: Implement the Runnable interface. 1. Define a class to implement the Runnable interface. 3. Create an object for MyThread2. Create Thread with MyThread2 as an argument to the constructor. Starting a thread
1.Define a class that implements the Runnable interfacepublic class MyThread2 implements Runnable{
@Override
public void run(a) {
for(int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
// This class implements only the runable interface and does not inherit the Thread class}}}Copy the code
public class MyThreadDemo2 {
public static void main(String[] args) {
//2: Override the run() method in MyRunnable
MyThread2 my = new MyThread2();
//3: Create MyRunnable object
//4: Create a Thread object with MyRunnable as an argument to the constructor
// Thread t1 = new Thread(my);
// Thread t2 = new Thread(my);
//Thread(Runable target, String name)
Thread t1 = new Thread(my,"A");
Thread t2 = new Thread(my,"B");
// Start the threadt1.start(); t2.start(); }}Copy the code
The implementation of multithreading:
- Inherited Tread class
- Implement the Runable interface
The Runable interface has the following advantages:
- Avoid the limitations of Java single inheritance
- Suitable for a number of the same program code to deal with the same resource situation, the thread and program code, data effective separation, a better reflection of the object facing design ideas
1.4 Setting and Obtaining the thread name
Methods of setting and getting the name of a Thread in the Thread class
- Viod setName(String name): Changes the name of this thread to equal the parameter name
- String getName(): Returns the name of the thread
- Alternatively, the thread name 👇 can be set via the constructor
MyThread classpublic class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
Copy the code
Main //Thread (String name)
MyThread my1 = new MyThread(Thread 1 "");
MyThread my2 = new MyThread(Thread 2 "");
Copy the code
How do I get the thread name of the main() method? · Public static Thread currentThread(): returns a reference to the Thread object that is currently executing.
System.out.println("Thread.currentThread.getName()");
Copy the code
1.5 Thread Priority
There are two scheduling models for threads
- Time-sharing scheduling model: All threads take turns to use the CPU and allocate the CPU time slice equally for each thread
- Preemptive scheduling model: the line with higher priority uses CPU first. If the priority is the same, it will be random. The line with higher priority will acquire more time slices
Java uses a preemptive scheduling model
When there is only one CPU, the CPU can execute only one instruction at a time, and the thread can execute only if it is given a time slice. So multithreaded program execution is random.
The Thread class has a method to get the priority of a Thread:
methods | instructions |
---|---|
public final int getPriority(): | Put the priority back |
public final void setPriority(int newPriority) | Change priority |
The default thread priority is 5; It ranges from 1 to 10. A high thread priority only means that a thread has a high chance of acquiring a CPU time slice.
1.6 Thread Control
The method name | instructions |
---|---|
static void sleep( long millis ) | Is the number of milliseconds for which the current thread stops executing |
viod join( ) | Wait for the thread to die |
void setDaemon( boolean on) | Marked as daemons, the VM exits when all running threads are daemons |
1.7 Thread life cycle
Second, thread synchronization
2.1 Resolution of data security problems
Criteria for determining whether multithreaded programs have data security issues:
- Whether a multi-threaded environment
- Whether to share data
- Whether multiple statements operate on shared data
How to Solve: Create a secure environment
How to do this: lock code that operates on shared data so that only one thread can execute at a time
Java provides synchronous code blocks:
Synchronizd (arbitrary object) {code where multiple statements operate on shared data}Copy the code
Lock code. Any object can be considered a lock
Advantages and disadvantages of synchronization:
- Benefits: Solve multi-threaded data security problems
- Disadvantages: When there are many threads, each thread will determine the lock on the synchronization, which is a waste of resources and reduces efficiency.
2.2 Synchronization Method
Synchronized methods: add the synchronized keyword to methods
- Synchronized return value type Method name (parameter){}
- The lock object of the synchronized method is: this
Static methods: Add the synchronized keyword to static methods
- Static synchronized method name (parameter) {}
- The lock object of the step static method is: class name.class
2.3 Thread-safe classes
StringBuffer:
- Thread-safe, mutable character sequences
- JDK5 starts, replaced by StringBuilder. The StringBuilder class is usually used because it supports all the same operations, but it is faster because no synchronization is performed
Vector:
- The underlying data is array-ArrayList
- Starting with The Java2 platform V1.2, the class improved the List interface and became a member of the Collections Framework. Unlike the new collection implementation, vectors are synchronized. If a thread-safe implementation is not required, ArrayList is recommended instead.
Hashtable:
- This class implements a hash table that maps keys to values. Any non-null object can be used as a key or value
- Since Java2 platform V1.2, this class has been improved to implement the Map interface and become a member of the Collection Framework. Instead of implementing the new collection, the Hashtable is synchronized. If a thread-safe implementation is not required, HashMap is recommended instead.
2.5 the Lock Lock
A new Lock object Lock is provided in JDK5. Lock implementations provide a wider range of locking operations than can be obtained using synchronized methods and statements.
- Void lock() : obtains the lock
- Void unlock() : Releases the lock
ReentrantLock: ReentrantLock: ReentrantLock: ReentrantLock: ReentrantLock: ReentrantLock
- ReentrantLock() : Creates an instance of ReentrantLock
3. Producers and consumers
Producer consumption pattern is a very classical multi-thread cooperation pattern. There are two main types of threads:
- One is the producer thread used to produce data
- One is the consumer thread used to consume data
To understand the relationship between producers and consumers, a shared data area, like a warehouse, is often used.
- Producers produce data and place it directly in the shared data area without concern for consumer behavior
- Consumers get their data directly from the shared data region without caring about the behavior of the producer
3.1 Overview of producer-consumer model
To represent the wait and wake up of production and consumption, Java provides several methods to use. These methods are the wait and wake up methods of the Object class:
The method name | instructions |
---|---|
void wait( ) | Causes the current thread to wait until another thread calls notify0 or Notifyl0 on the object |
void notify( ) | Wakes up a single thread that is waiting for the object monitor |
void notifyAll( ) | Wakes up all threads that are waiting on the object monitor |