Program, process, thread
Program: static concept, a collection of instructions written in a language, a piece of static code
Process: the execution process of a program or the program being executed. It is a dynamic process with a life cycle
Thread: a process is refined into a thread, which is the internal execution path of a program
Concurrency and parallelism: concurrency is executed in turn and parallel is executed at the same time
Single core CPU and multi-core CPU
Parallelism and concurrency
Advantages multithreading
Create thread
There are two ways to create a Thread, but starting a Thread can only call the start method in the Thread class object in one way
The first way to create a Thread is to create a class that inherits the Thread class and overrides the run() method. The run method is equal to the main method in the new Thread and is the starting point and end point of program execution
The starting thread manually calls the start() method of the current thread object!!! Not a run method
// Create thread class object Thread t = new Test_01(); // Start thread t.start(); class Test_01 extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("run->" + i); } } }
The second way is to implement the Runnable interface, override the run method to start the Thread and call the start method of Thread
// Create thread class object Thread t = new Thread(new Test_02()); // Start thread t.start(); class Test_02 implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("run->" + i); } } }
Start(): start thread
setName(): set the name of the thread. The default is thread-0, thread-1, and so on
getName(): get the name of the thread
setPriority(): set priority, 1-10, 10 levels, 1 min, 10 max
getPriority(): get priority
Static currentThread(): get the memory address of the current thread (thread object)
Static sleep(): put the current thread into sleep. The parameter is the number of milliseconds
Thread t1 = new Test_03(); Thread t2 = new Test_03(); // Set the name, preferably before startup, the default Thread-0, and so on t1.setName("t1"); t2.setName("t2"); // start-up t1.start(); t2.start(); // set priority t2.setPriority(10); t1.setPriority(1); Thread.currentThread().setPriority(10); for (int i = 0; i < 10; i++) { // currentThread obtains the current thread object and static method, which means that it has nothing to do with who calls it, and the thread object will be obtained on which thread it is written System.out.println(Thread.currentThread().getName() + "->" + i); try { // Sleep allows the current thread to sleep. Static methods have nothing to do with who calls them. They sleep on which thread they are written on Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } class Test_03 extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { // Get name System.out.println(this.getName() + "->" + i); try { // Sleep allows the current thread to sleep. Static methods have nothing to do with who calls them. They sleep on which thread they are written on Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
life cycle
Thread. Is used in JDK The state class defines several states of a thread
To implement multithreading, you must create a new Thread object in the main Thread. The Java language uses the objects of Thread class and its subclasses to represent threads. In a complete life cycle, it usually experiences the following five states:
New: when the object of a Thread class or its subclass is declared and created, the new Thread object is in the new state
Ready: after the thread in the newly created state is started (), it will enter the thread queue and wait for the CPU time slice. At this time, it has met the running conditions, but it has not been allocated CPU resources
Run: when the ready thread is scheduled and obtains CPU resources, it enters the running state. The run() method defines the operation and function of the thread
Blocking: in a special case, when the input / output operation is suspended or executed artificially, give up the CPU and temporarily suspend its execution to enter the blocking state
Death: the thread completes all its work or the thread is forcibly terminated in advance or ends with an exception
Thread control
sleep() puts the current thread into sleep, static method, and the number of sleep milliseconds passed in
interrupt(): forcibly wakes up the sleeping thread and throws an exception
Thread t1 = new Thread(new Test_04()); t1.start(); try { Thread.sleep(1000); // Wake up t1 thread t1.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); }
Thread t = new Test_004(); Thread t2 = new Test_004(); t.setName("t1"); t2.setName("t2"); t.start(); t2.start(); // The current thread needs to wait for the t thread to execute before continuing t.join(); for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + " -> " + i); }
Thread.yield(): a static method that gives up the current execution time slice for other threads to execute
1 static method, where to write, where to give way
2. The same priority gives way, and different priorities do not give way
The priority is 5 by default, and the subclass inherits the priority of the parent class
Thread t = new Thread(new Test_05()); t.setName("t1"); t.start(); for (int i = 0; i < 10; i++) { // Give way Thread.yield(); System.out.println(Thread.currentThread().getName() + "->" + i); }
End thread
stop: terminating a thread can easily lead to deadlock, so it is outdated and is not recommended
It is recommended to end with an identifier
Test_06 t = new Test_06(); t.start(); try { Thread.sleep(5000); // t.stop(); t.flag=false; } catch (InterruptedException e) { e.printStackTrace(); } // Flag, false terminates boolean flag = true; @Override public void run() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); while (flag) { System.out.println(sdf.format(new Date())); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
Thread synchronization lock
Thread synchronization: when multiple threads may operate on the same data, the current operation needs to be synchronized in order to ensure data consistency
The essence of thread synchronization is data synchronization, which is a security mechanism
In particular, the synchronization mechanism must be used to change the data. It doesn't matter if it's just a query
Asynchronous programming
Threads are completely independent of each other and work at the same time, but they do not affect each other
Synchronous programming
Threads are not independent, but they are carried out at the same time, but they affect each other. Therefore, at this time, it is necessary for a thread to execute an operation alone before allowing other threads to execute
Synchronization condition
1 must be multithreaded
2 it must be possible for multiple threads to operate a shared data at the same time
3. It mainly involves data change operations
Method lock: synchronized modifier, a modified method that cannot be executed by multiple threads at the same time
If you access a locked member method in an object, all locked member methods in the object cannot be accessed by other threads
If you access the locked static methods in a class, all the locked static methods in the class cannot be accessed by other threads
// Withdraw money public void withDraw(double money) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } // Lock the current object. In the current object, all locked member methods will also be locked // If the whole method is locked, multiple threads cannot enter the method at the same time // If there is a lot of code in our method, but only two sentences need to be synchronized, the efficiency will be too low // In this way, multiple threads can still enter the method at the same time, but statement blocks cannot be executed at the same time synchronized (this) { // Class lock // synchronized (class name. class) {} balance -= money; System.out.println(Thread.currentThread().getName() + "--> Successful withdrawal,surplus : " + getBalance()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } // Lock // xxxx // Unlock } }
Lock object
// Lock object Lock lock = new ReentrantLock(); // Withdraw money public void withDraw(double money) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } // Lock lock.lock(); try { balance -= money; System.out.println(Thread.currentThread().getName() + "--> Successful withdrawal,surplus : " + getBalance()); } finally { // Unlock lock.unlock(); }
Daemon thread
Daemon thread: also known as bottom thread
During the operation of each program, a daemon thread will be opened by default to monitor our normal program
When no thread executes, the JVM needs to exit, and the daemon thread will also exit
The setDaemon() method is provided in the Thread class, which can set a Thread as a daemon Thread
// Set t1 as daemon thread t1.setDaemon(true);
timer
// 1 create timer Timer timer = new Timer(); String str = "2021/04/16 15:51:12 000"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss SSS"); Date date = sdf.parse(str); // 1. For the task object to be executed, the task class needs to inherit the TimerTask class and override the run method, which contains the things to be completed // 2. The start time of execution can be passed in the time object (the execution starts at the specified time) or the number of milliseconds (how long after the execution) // 3 interval timer.schedule(new logTimerTask(), date, 1000);