This is the 23rd day of my participation in the August More Text Challenge.More challenges in August
Java Multithreaded programming
Java provides built-in support for multithreaded programming. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel.
Multithreading is a special form of multitasking, but it uses less resource overhead.
Another thread-related term is defined here – process: a process consists of memory allocated by the operating system and contains one or more threads. A thread cannot exist on its own; it must be part of a process. A process runs until all non-daemons have finished running.
Multithreading can satisfy programmers to write efficient programs to make full use of CPU.
What is Java multithreading?
1. Processes and threads
▶ process
- When a program is run, a process is started, such as qq, Word
- The program consists of instructions and data, instructions to run, data to load, instructions are loaded by THE CPU to run, data is loaded into memory, instructions run by the CPU scheduling hard disk, network and other devices
▶ thread
- A process can be divided into multiple threads
- A thread is a stream of instructions, the smallest unit of CPU scheduling, executed by the CPU one instruction at a time
Parallelism and concurrency
▶ Concurrency: When running multiple threads on a single-core CPU, time slices can be switched quickly. Threads take turns executing the CPU
▶ Parallelism: When a multi-core CPU runs multiple threads, it truly runs at the same time
Creating multiple threads
Thread class inheritance
public class test0 { public static void main(String[] args) { Thread MyThread = new MyThread(); MyThread.start(); } } class MyThread extends Thread { @Override public void run() { System.out.println("hello myThread" + Thread.currentThread().getName()); }}Copy the code
Implement Runnable
public class test0 { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } } class MyRunnable implements Runnable{ @Override public void run(){ System.out.println("hello myRunnable" + Thread.currentThread().getName()); }}Copy the code
suspended
Threads are paused in Java by calling the sleep method of the java.lang.Thread class. This method suspends the currently executing thread for a specified period of time, and if the thread holds the lock, the lock is not released until the sleep method ends.
Java example:
public class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.print(i + " "); try { Thread.sleep(1000); // The main thread is suspended for 1000ms} catch (InterruptedException e) {}}}}Copy the code
In the code above, when the main thread callsThread.sleep(1000)
After the thread is suspended, if it isinterrupt
, will throwInterruptedException
The exception.
The mutex
In Java, the synchronized keyword is used for mutually exclusive shared operations of threads. The architecture in which threads share mutex is called monitor, and acquiring locks is sometimes referred to as “own monitoring.”
Each lock is held by only one thread at a time. Note: During execution of a synchronized method or declaration, the thread releases the lock if the program encounters any exceptions or returns.
1. Synchronized method
Public synchronized void deposit(int m) {system.out.print ("This is synchronized method."); }Copy the code
Note: Synchronized instance methods use this lock (the current object) as a shared mutex for threads.
Public static synchronized void deposit(int m) {system.out.print ("This is synchronized static method."); }Copy the code
Note: Synchronized class methods use class object locks (that is, class objects of the current class) to act as shared mutex for threads. Class (inherited from java.lang.class) is used as the lock, as in the example above.
2. Synchronized statement
public void deposit(int m) { synchronized (this) { System.out.print("This is synchronized statement with this lock."); } synchronized (Something.class) { System.out.print("This is synchronized statement with class lock."); }}Copy the code
Note: Synchronized declarations can use arbitrary locks. In the above example, object locks (this) and class locks (something-class) are used respectively.
3. Wait and notify
Object has two important interfaces :Object.wait() and Object.notify().
When the wait() method is called on an object instance, the current thread waits on that object. Until another thread calls notify() or notifyAll() on the object. NotifyAll () differs from notify() in that it wakes up all threads waiting for the object, whereas notify() wakes up only one random thread waiting for the object.
Wait (), notify(), and notifyAll() are all required in synchronized statements
4, interrupt
The java.lang.Thread class has an interrupt method that is called directly on the Thread. InterruptedException is thrown when the interrupted thread is sleeping or waiting. In fact, the interrupt method simply changes the interrupt status of the target thread. Methods that throw InterruptedException, such as Wait, sleep, join, etc., constantly check the value of the interrupt status inside the method.
- Interrupt method
Thread instance method: another Thread must obtain the instance of the called Thread and make the call. In fact, it only changes the internal interrupt state of the called thread;
- Thread. Interrupted method
Thread class method: must be called within the current executing Thread. This method returns the internal interrupt status of the current Thread and then clears the interrupt status (set to false).
- IsInterrupted method
Thread instance method: used to check the interrupt status of the specified Thread. Returns true if the thread is interrupted; Otherwise return false.