当前位置:网站首页>Day21 multithreading

Day21 multithreading

2022-07-07 12:48:00 Xiaobai shelter

1. Multithreading
1.1 Program , process , Threads
Program : A collection of commands , In order to complete the specified function , A program is a static concept , Usually stored in the hard disk
process : Running programs , It's a dynamic concept , Need to be saved in memory , The operating system assigns the corresponding PID, When we close a process directly , The process will be destroyed in the running memory
Threads : In a program , Different branches , If the same time node allows multiple threads to execute at the same time , We become multi-threaded
stay java in ,main Method start execution , It's just a thread , Become the main thread

1.2 Parallel and concurrent
parallel : Multiple CPU, Perform multiple tasks at the same time
Concurrent : One CPU, Perform multiple tasks at the same time

Multithreading parallel , must CPU Number , Greater than or equal to 2 Talent
Single core CPU There is no multithreading

1.3 Single core CPU And multicore CPU
① Single core CPU, It's actually a fake multithreading , Because in a unit of time , Only one thread task can be executed As we go CPU In operation , because CPU The practice unit is very short , We can't feel it
② If it's multicore , In order to better play the efficiency of multithreading .( Today's servers are multi-core )
③ One Java Applications java.exe, There are at least three threads :main() The main thread ,gc() Garbage collection thread , Exception handling threads . Of course, if something goes wrong , Will affect the main thread

1.4 Advantages and disadvantages of multithreading and execution scenarios
background : Single core CPU For example , Only use a single thread to complete multiple tasks successively ( Call multiple parties Law ), It must take less time than using multiple threads to complete , Why is it still necessary to multithread ?

The advantages of multithreading programs :
1. Improve application response . More meaningful for graphical interfaces , Enhance the user experience .
2. Improving computer systems CPU Utilization ratio
3. Improve program structure . Divide a long and complex process into multiple threads , Independent operation , Conducive to understanding and
modify

 Application scenarios 

Programs need to perform two or more tasks at the same time .
When the program needs to implement some tasks that need to wait , Such as user input 、 File read and write operations 、 Network operating 、 Search, etc .
When you need some background programs .

1.5 Thread creation
There are two kinds of thread creation

The first one is : Create a class , Inherit Thread class , And overwrite run Method
run Method It's like... In a new thread main Method

     // The first one is 
class Processor extends Thread{
    
	// Member method 
	public void run(){
    
		for(int i=0;i<10;i++){
    
			System.out.println(" Test thread "+i);
		}
	}
}
// Create thread class objects 
    	Thread t1=new Processor();
    	// call start Method , Start thread 
    	t1.start();
``

 The second kind   Runnable

```java
     // The second kind 
class Processor_01 implements Runnable{
    

		@Override
		public void run() {
    
          for(int i=0;i<10;i++){
    
        	  System.out.println(" Test thread -->"+i);
          }
		}
}
 // Static methods , The method of implementing the second thread 
    public static void test_02(){
    
    	// Create an implementation class object 
    	Processor_01 p=new Processor_01();
    	// Create thread class objects 
    	Thread t1=new Thread(p);
    	// Start thread 
    	t1.start();

1.5.3 The difference between inheritance and Implementation
public class Thread extends Object implements Runnable
difference : Inherit Thread: Thread code storage Thread Subclass run In the method
The benefits of the implementation
The limitation of single inheritance is avoided
Multiple threads can share objects of the same interface implementation class , It is very suitable for multiple threads to process the same resource

1.6 Priorities and common methods
The priority level of the thread
MAX_PRIORITY:10
MIN _PRIORITY:1
NORM_PRIORITY:5
Methods involved
getPriority() : Returns the thread priority value
setPriority(int newPriority) : Change the priority of a thread
explain
Inherits the priority of the parent thread when the thread is created
Low priority is only a low probability of obtaining scheduling , It doesn't have to be called after a high priority thread

1.6.2 Common methods
Common methods used in threads

  • getName: Get the name of the thread
  • setName: Set the name of the thread , If not set , The default is Thread-0 Start , In turn, increasing
  • setPriority(): set priority ,java There is 1-10,10 Two priority levels
  •        MIN_PRIORITY=1
    
  •        NORM_PRIORITY=5
    
  •        MAX_PRIORITY=10
    

*getpriority(): Get priority level
*static currentThread(): Get the current thread object
*static sleep(): Put the current thread to sleep . Pay attention to sleep Method , must do try catch operation
*currentThread and sleep It's a static method , It means that it has nothing to do with which object is called
*currentThread: In which thread , Just get which thread object
*sleep: In which thread , Just sleep on which thread , Parameter is long Type of milliseconds
1.6.3 Usage mode

public class Thread_02_Priority {
    
    public static void main(String args[]){
    
    	// Creating thread objects 
    	Thread t1=new Processer();
    	// Set the name 
    	t1.setName("t1");
    	// Set the priority to 10
    	t1.setPriority(10);
    	// Set up main The priority of 1
    	Thread.currentThread().setPriority(1);
    	// Start thread 
    	t1.start();
    	
    	for(int i=0;i<10;i++){
    
    		try{
    
    			// sleep 500 millisecond 
    			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{
    
	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);
		}
	}
}

1.7 Thread stop
stop: Terminate the execution of a thread , This method is out of date , It is not recommended to use , Because it may cause deadlock
Therefore, identifiers are generally used to solve

public class Thread_03_Stop {
    
    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(5000);
			//t1.stop
			p.flag=true;
		} catch (InterruptedException e) {
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}

1.7.2 Thread merge
join: Thread merge , Let the current thread wait for the specified thread to finish executing , And go on with it

public class Thread_04_Join {
    
    public static void main(String args[]) throws InterruptedException{
    
    	Thread t1=new Processer_04();
    	t1.setName("t1");
    	t1.start();
    	// Come here ,main Just wait t1 After the thread has finished executing , And go on with it 
    	t1.join();
    	for(int i=0;i<10;i++){
    
    		try{
    
    			// sleep 500 millisecond 
    		Thread.sleep(500);
    		}catch(InterruptedException e){
    
    			e.printStackTrace();
    		}
    		System.out.println(Thread.currentThread().getName()+"-->"+i);
    	}
    	// Get the thread object and get the thread name 
// System.out.println(Thread.currentThread().getName()+"-->"+i);
    }
}

1.7.3 Yield
yield: Static methods , Pause the currently executing thread object , And execute other waiting processes

  • 1. Static methods , It means that it has nothing to do with the object call , Written in which thread , Which thread gives way
  • 2. Give way to the same priority , Different priorities do not give way , Of course, different priorities will not use this method
public class Thread_05_Yield {
    
    public static void main(String args[]){
    
    	// Create thread 
    	Thread t1=new Thread(new Processor_05());
    	t1.setName("t1");
    	// Set up t1 Threads and main Consistent thread priority 
    	t1.setPriority(5);
    	Thread.currentThread().setPriority(5);
    	// start-up 
    	t1.start();
    	for(int i=0;i<10;i++){
    
    		// Abdication 
    		Thread.yield();
    		System.out.println(Thread.currentThread().getName()+"-->"+i);
    	}
    }
}

1.8 Thread synchronization
Thread synchronization : When multiple threads may operate on the same data at the same time , In order to guarantee the data

  •         Uniformity , Synchronous execution is required 
    
  • The essence is to synchronize data , It's a security mechanism
    * Asynchronous programming : Threads are completely independent , There is no influence on each other
    * Synchronous programming : Threads are not completely independent , There may be mutual influences

* Synchronized scenes :1 Must be multithreaded ( There must be concurrency , It's possible to make mistakes )

  •       2  The possibility that multiple threads may operate on the same data at the same time 
    
  •       3  Especially when changing data at the same time , Query doesn't matter 
    

1.9 Method lock

class MyClass_01{
    
	public synchronized void m1(){
    
		try {
    
			Thread.sleep(3000);
		} catch (InterruptedException e) {
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(" The lock m1 Method ");
	
	}
	public synchronized void m2(){
    
		System.out.println(" The lock m2 Method ");
	}
	public  void m3(){
    
		System.out.println(" Unlocked m3 Method ");
	}
}

1.9.2 Statement block lock
If In this method , When only part of the code needs to be synchronized , If you pass synchronized modification , Efficiency will be greatly reduced
therefore We can lock through the statement block , Lock only the corresponding code , In this way, other code in the method can still be executed at the same time , Improved efficiency

1.9.3 synchronized
synchronized( object ){} Member statement block lock

  • When accessing a locked member method or member statement block lock in an object , Then all locked member methods in the object
  • And member statement block lock All locked
  • synchronized( Class name .class){} Static statement block lock
  • When accessing a class , When locking static methods or static statement blocks , Then all static methods and static statement blocks locked in the object , All locked

1.10 Lock
1.10.1 Advantages and disadvantages
lock It's a display lock , It needs to be opened and closed manually synchronized It's an implicit lock , Auto on , Automatically close after execution
*
*lock Only code block locks , and synchronized Support method and code block locks
*lock lock , need JVM Spend less time on resource scheduling , The performance is relatively good , And it has good scalability
* Order of use :Lock lock –> Sync block lock –> Fang FA Suo
1.10.2 Use

class Account1{
    
	// balance 
	private double balance;
	// Create lock object 
	Lock lock=new ReentrantLock();
	public void withDraw(double money) {
    
		System.out.println(Thread.currentThread().getName()+"  Came in ");
		//  Start syncing 
		lock.lock();
		try {
    
			Thread.sleep(1000);
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
		//  Statement block lock 
		//  Balance minus withdrawal amount 
		double after = balance - money;
		//  The new balance is copied to the balance 
		balance = after; // 2000
		System.out.println(Thread.currentThread().getName() + "  Take money successfully , Withdraw money  : "
				+ money + " element , The remaining  : " + balance + "  element  ");
		//  Unlock 
		lock.unlock();
	}

1.11 Timer task
1.11.1 summary
Timer : Planning tasks
*

  • As long as there is a planned task , It will open a thread , time , At the appointed time , The thread completes this task

1.11.2 Use

public class Thread_09_Timer {
    
   public static void main(String args[]){
    
	   //1  What to do , That is, the task object 
	   //2  When to start doing ,1000*5  It starts in five seconds 
	   //3  Time interval between , How often do you do  1000*3 Every three seconds 
	   Timer t=new Timer();
	   t.schedule(new LogTimerTask(), 1000*5, 1000*3);
   }
}
// Create tasks 
class LogTimerTask extends TimerTask{
    

	@Override
	public void run() {
    
		// TODO Auto-generated method stub
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=sdf.format(date);
		System.out.println(time);
	}
	
}

原网站

版权声明
本文为[Xiaobai shelter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130617040349.html