1 program, process, thread
Program: a set of commands. In order to complete the specified functions, the program is a static concept and is generally stored in the hard disk
Process: a running program is a dynamic concept and needs to be saved in memory. The operating system will allocate the corresponding PID. When we close a process directly, the process will be destroyed in the running memory
Thread: in a program, different execution branches. If multiple threads are allowed to execute at the same time at the same time node, we call it supporting multithreading
In Java, the main method starts to execute, which is a thread called the main thread
2 concurrency and parallelism
Parallel: multiple CPU s execute multiple tasks at the same time
Concurrency: one CPU executes multiple tasks at the same time
Multithreading parallelism requires a CPU greater than or equal to 2
Single core CPU has no multithreading
3 advantages and disadvantages of multithreading
advantage:
Improve application response. It is more meaningful to the graphical interface and can enhance the user experience.
Improve the utilization of computer system CPU
Improve program structure. The long and complex process is divided into multiple threads and run independently, which is conducive to understanding and modification
Disadvantages:
The program needs to perform two or more tasks at the same time.
When the program needs to realize some tasks that need to wait, such as user input, file reading and writing operation, network operation, search, etc.
When you need some programs running in the background
4 thread creation
public static void main(String[] args){ test_02(); } public static void test_02(){ //Create implementation class object Processor_01 p = new Processor_01(); //Create thread class object Thread t1 = new Thread(p); //Start thread t1.start(); for(int i =0; i<10;i++){ System.out.println("main thread " +i); } } public static void test_01(){ //Create thread class object Thread t1 = new Processor(); //Call the start method to start the thread t1.start(); for(int i =0; i<10; i++){ System.out.println("main thread -->" + i); } } } /** * The first is to create a class, inherit the Thread class, and override the run method * run Method is equal to the main method in the new thread */ class Processor extends Thread{ @Override public void run(){ for(int i= 0; i<10; i++){ System.out.println("Test thread---" +i); } } } /** * Second, create a class to implement the Runnable interface and override the run method * run The method is the main method of the new line */ class Processor_01 implements Runnable{ @Override public void run(){ for(int i= 0; i<10; i++){ System.out.println("Test thread 11" +i); } } }
5 thread priority
setPriority(): set priority. java has 1-10 priorities
* MIN_PRIORITY = 1
* NORM_PRIORITY = 5
* MAX_PRIORITY = 10
6 common methods
public static void main(String[] args){ //Create thread object Thread t1 = new Processer(); //set name t1.setName("t1"); //Set priority to 10; t1.setPriority(10); //Set the priority of main to 1 Thread.currentThread().setPriority(1); //Start thread t1.start(); for(int i =0; i<10; i++){ try{ //Sleep for 500 seconds Thread.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } //Get the thread object and get the thread name System.out.println(Thread.currentThread().getName()+"+++++" +i); } } } class Processer extends Thread{ @Override public void run(){ for(int i =0; i< 10; i++){ try{ Thread.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "----" +i); } }
7 thread stop:
Stop: terminates the execution of a thread. This method is outdated and is not recommended because it may cause deadlock
Identifier is generally used to solve the problem
public static void main(String[] args){ Processer_03 p = new Processer_03(); Thread t1 = new Thread(p); t1.setName("t1"); t1.start(); try{ Thread.sleep(7000); p.flag = true; }catch(InterruptedException e){ e.printStackTrace(); } } } class Processer_03 implements Runnable{ //Add an identifier to identify whether to terminate the thread boolean flag = false; @Override public void run(){ for(int i =0;true; i++){ //Determine whether to terminate if(flag){ System.out.println(Thread.currentThread().getName()+"The thread has been terminated"); return; } try{ Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+ "---" +i); }catch(InterruptedException e){ e.printStackTrace(); } } }
8 thread merging
join: thread merging allows the current thread to wait for the specified thread to finish executing and continue executing
public static void main(String [] args) throws InterruptedException{ Thread t1 = new Processer_04(); t1.setName("t1"); t1.start(); //Come here. main will wait for the t1 thread to finish executing before continuing t1.join(); for(int i =0; i<10;i++){ try{ //Sleep for 300 milliseconds Thread.sleep(300); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"++++" +i); } } } class Processer_04 extends Thread{ @Override public void run(){ for(int i =0; i<10; i++){ try{ //Sleep for 500 milliseconds Thread.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"----" +i); } }
9Yield
yield: a static method that pauses the currently executing thread object and executes other waiting threads
1. Static method: it means that it has nothing to do with which object is called. In which thread it is written, which thread will give way
2 give way to the same priority, but not to different priorities
public static void main(String[] args){ //Create thread Thread t1 = new Thread(new Processor_05()); t1.setName("t1"); //Set the priority of t1 thread and main thread to be consistent t1.setPriority(5); Thread.currentThread().setPriority(5); t1.start(); for(int i =0; i<10; i++){ //Give way Thread.yield(); System.out.println(Thread.currentThread().getName()+"====="+i); } } } class Processor_05 implements Runnable{ @Override public void run(){ for(int i =0; i< 8; i++){ System.out.println(Thread.currentThread().getName()+"----"+i); }
10 thread synchronization
Thread synchronization: when multiple threads may operate the same data at the same time, synchronous execution is required to ensure data consistency
The essence is to synchronize data, which is a security mechanism
Asynchronous programming: threads are completely independent and have no influence on each other
Synchronous programming: threads are not completely independent and may affect each other
Synchronous scenario: 1. It must be multithreaded (there must be concurrency to make mistakes). 2. It is possible for multiple threads to operate the same data at the same time
3 especially when data is changed at the same time, query doesn't matter
11 solutions
11.1 method # use synchronized
class MyClass_01{ public synchronized void m1(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Locked m1 method"); } public synchronized void m2(){ System.out.println("Locked m2 method"); } public void m3(){ System.out.println("Unlocked m3 method"); } }
11.2 statement block lock
If only part of the code needs to be synchronized in this method, the efficiency will be greatly reduced if it is modified by synchronized
Therefore, we can lock only the corresponding code through the statement block lock. In this way, other codes in the method can be executed at the same time, and the efficiency is improved
class Processor_08 implements Runnable{ MyClass_01 mc; public Processor_08(MyClass_01 mc) { this.mc = mc; } @Override public void run() { //Gets the name of the thread String name = Thread.currentThread().getName(); if(name.equals("t1")){ mc.m1(); }else if(name.equals("t2")){ mc.m2(); } if(name.equals("t3")){ mc.m3(); } }
12 lock
- Starting with JDK 5.0, Java has provided a more powerful thread synchronization mechanism -- by explicitly defining the same thread
Step Lock object to achieve synchronization. Synchronous locks use Lock objects as.
- java.util.concurrent.locks.Lock interface is a tool that controls multiple threads to access shared resources. Locks provide exclusive access to shared resources. Only one thread can lock the lock object at a time. Threads should obtain the lock object before accessing shared resources.
ReentrantLock class implements Lock. It has the same concurrency and memory semantics as synchronized. ReentrantLock is commonly used in thread safety control, which can explicitly add and release locks
class Account1{ //balance private double balance; //Create lock object Lock lock = new ReentrantLock(); public void wihtDraw(double money){ System.out.println(Thread.currentThread().getName()+"Come in"); //Start synchronization lock.lock(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //Statement block lock //Balance minus withdrawal amount double after = balance - money; //Copy new balance to balance balance =after; System.out.println(Thread.currentThread().getName() + " Successful withdrawal,withdraw money : " + money + "element,surplus : " + balance + " element "); //Unlock lock.unlock(); }
12.1 advantages and disadvantages
Lock is a display lock that needs to be opened and closed manually. synchronized is an implicit lock that opens automatically and closes automatically after execution
lock has only code block locks, while synchronized supports method or code block locks
Lock lock requires the JVM to spend less time on resource scheduling, with relatively good performance and good scalability
Usage order: Lock lock -- > sync code block Lock -- > method Lock
13 timer task
Timers: scheduling tasks
As long as there is a scheduled task, a thread will be started for timing. After reaching the specified time, the thread will complete the task
public class Thread_09_Time { public static void main(String[] args){ // 1. What to do is the task object // 2 when to start, 1000 * 5 is 5 seconds later // 3 interval. How often do you do 1000 * 3 every 3 seconds Timer t = new Timer(); t.schedule(new LogTimerTask(), 1000*5,1000*3); } } //Create task class LogTimerTask extends TimerTask{ public void run(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(date); System.out.println(time); } }