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

Day21 multithreading

2022-06-25 16:20:00 weixin_ forty-eight million six hundred and forty-four thousand

  1.   Multithreading
    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 call it supporting multithreading

stay Java in ,main Method start execution , It's just a thread , Called the main thread

    1.   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 Be greater than or equal to 2 Talent

Single core CPU There is no multithreading

    1.   Single core CPU Hetuohe CPU
    1. Single core CPU, It's actually a fake multithreading , Because in a unit of time , Only one thread can be executed The task of . for example : Although there are multiple lanes , But there is only one staff member in the toll station charging , Only charge Can pass , that CPU It's like a toll collector . If someone doesn't want to pay , Then the toll collector can Take him “ Hang up ”( Hang him , When he's figured it out , Ready for the money , Charge again ). But because CPU when The inter unit is very short , So I can't feel it .
    2. If it's multicore , In order to better play the efficiency of multithreading .( Today's servers are multi-core )
    3. 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.   Advantages, disadvantages and application scenarios of multithreading

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

  1. Programs need to perform two or more tasks at the same time .
  2. 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 .

 

  1. When you need some background programs .
    1.  Runnable  Thread creation
      1. public static void main(String[] args){
        		test_02();
        	}
        	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();
        		for(int i = 0; i<10 ; i++){
        			System.out.println("main Threads -->"+i);
        		}
        	}
        	public static void test_01(){
        		// Create thread class objects 
        		Thread t1 = new Processor();
        		// call start Method   Start thread 
        		t1.start();
        		for(int i = 0;i<10;i++){
        			System.out.println("main Threads -->"+i);
        		}
        	}
        
        }
        /**
         *  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 
         */
        class Processor extends Thread {
        	@Override
        	public void run() {
        		for (int i = 0; i < 10; i++) {
        			System.out.println(" Test thread -->" + i);
        		}
        	}
        }
        
        /**
         *  The second kind   Create a class , Realization Runnable Interface , And overwrite run Method 
         * 
         * run Method   It's like... In a new thread main Method 
         * 
         */
        class Processor_01 implements Runnable {
        	@Override
        	public void run() {
        		for (int i = 0; i < 10; i++) {
        			System.out.println(" Test thread -->" + i);
        		}
        	}

          1. The difference between inheritance and Implementation
      2.  public class Thread extends Object implements Runnable

      3. difference
        • Inherit Thread: Thread code storage Thread Subclass run In the method .
        • Realization Runnable: The thread code exists in the subclass of the interface run Method .
      4. The benefits of the implementation
        • The limitation of single inheritance is avoided
        • Multiple threads can share objects of the same interface implementation class , Perfect for multiple identical lines To deal with the same resource .
        1.   Priorities and common methods
          1.   Priority Overview
      5. The priority level of the thread

        1. MAX_PRIORITY10
        2. MIN _PRIORITY1
        3. NORM_PRIORITY5
      6. Methods involved

        1. getPriority() Returns the thread priority value
        2. setPriority(int newPriority) Change the priority of a thread
      7. explain

        1. Inherits the priority of the parent thread when the thread is created
        2. Low priority is only a low probability of obtaining scheduling , It doesn't have to be called after a high priority thread

 

/**
 * 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 
 * 
 * currentThread and sleep  It's a static method , signify   It has nothing to do with which object to call 
 * 
 * currentThread :  In which thread , Just get the object of which thread 
 * sleep :  In which thread , Just sleep on which thread , Parameter is long Type of milliseconds 
 */
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 {
		@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);
			}
		}
	}

 

    1. Life cycle

JDK of use Thread.State Class defines several states of a thread

To achieve multithreading , A new thread object must be created in the main thread .Java Language use Thread class And its subclasses to represent threads , In its whole life cycle, it usually goes through the following 5、 ... and States

newly build : When one Thread When an object of class or its subclass is declared and created , The new thread object is in the new state state

be ready : The thread in the newly created state is start() after , Will enter the thread queue to wait CPU Time slice , At this point, it has the conditions to run , It's just not assigned to CPU resources

function : When the ready thread is scheduled and gets CPU Resource time , It goes into operation , run() Method defines the line The operation and function of the program

Blocking : In some special case , When an I / O operation is suspended or executed artificially , Give up CPU And temporarily suspend their own execution , Go into blocking mode

Death : The thread has completed all its work or the thread has been forced to terminate ahead of time or an exception has occurred leading to the end of the thread

      1.   Thread stop
/**
 * stop :  Terminate no thread execution , 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) {
			e.printStackTrace();
		}
	}
}

class Processer_03 implements Runnable {
	//  Add a logo , Identify whether to terminate the thread 
	boolean flag = false;

	@Override
	public void run() {
		for (int i = 0; true; i++) {
			//  Judge whether to terminate 
			if (flag) {
				System.out.println(Thread.currentThread().getName() + " Thread terminated ");
				return;
			}
			try {
				Thread.sleep(1000);
				System.out
						.println(Thread.currentThread().getName() + "-->" + i);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
      1.   Thread merge
      2. /**
         * 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();
        			}
        			//  Get the thread object and get the thread name 
        			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 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);
        		}
        	}
        }

         Yield

        1. /**
           * yield :  Static methods , Pause the currently executing thread object , And execute other waiting threads 
           * 
           * 1  Static methods , It means that there is no official thanks for calling with that object , In which thread is it written , Which thread gives way 
           * 
           * 2  Give way to the same priority , Different priorities do not give way 
           */
          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);
          		}
          	}
          }
          class Processor_05 implements Runnable{
          	@Override
          	public void run() {
          		for (int i = 0; i < 10; i++) {
          			System.out.println(Thread.currentThread().getName()+"-->"+i);
          		}
          	}
          }

          Thread synchronization : When multiple threads may operate on the same data at the same time , To ensure data consistency , 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.   Thread synchronization
            1.   summary
        2. Problem presentation

          The uncertainty of multi thread execution causes the instability of execution result

          Sharing of ledger by multiple threads , This will result in incomplete operation , It will destroy the data

原网站

版权声明
本文为[weixin_ forty-eight million six hundred and forty-four thousand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190534174047.html