Multithreading basics notes

One 、 Threads

1. Basic concepts

  • Program (program): To accomplish a specific task 、 A collection of instructions written in a language . That is to say A piece of static code , Static objects .
  • process (process): It's an execution of the program , or A running program . It's a dynamic process : It has its own production 、 The process of existence and extinction ( Life cycle ).
    • Process as the unit of resource allocation , At run time, the system allocates different memory areas for each process .
  • Threads (tread): Processes can be further refined into threads , It's an execution path inside a program .
    • If a process executes multiple threads at the same time , It supports multithreading .
    • Thread as the unit of scheduling and execution , Each thread has its own Run stack and Program counter (pc), Low cost of thread switching .
    • Multiple threads in a process share the same memory unit / Memory address space --> They allocate objects from the same heap , You can access the same variables and objects . This makes communication between threads easier 、 Efficient . But the system resources shared by multiple threads may bring security risks .
  • Single core CPU And polynuclear CPU The understanding of the :
    • Single core CPU, It's actually a fake multithreading , Because in a unit of time , Only one thread can be executed . for example : There are multiple lanes , But there is only one staff member in the toll station charging , You can only pass if you pay a fee , that CPU It's like a toll collector , If someone doesn't want to pay , Then the toll collector can take him “ Hang up “( Wait until he's ready to pay ). But because CPU The time unit is very short , So I can't feel it .
    • Multicore CPU, In order to better play the efficiency of multithreading .
    • 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 .
  • Parallelism and concurrency
    • parallel : Multiple CPU Perform multiple tasks at the same time .
    • Concurrent : One CPU( Using time slices ) Perform multiple tasks at the same time .

2. Advantages of multithreading

  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 , Easy to understand and modify .

3. When multithreading is needed

  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 、 Network operating 、 Search, etc .
  3. When you need some background programs .

4. Thread creation

Mode one : Inherited from Thread class

  1. Create an inheritance from Thread Subclasses of classes
  2. rewrite Thread Class run Method --> Declare the operation performed by this thread in run() in
  3. establish Thread Object of subclass of class
  4. Call... Through objects start Method

Example :

//1. Create an inheritance from Thread Subclasses of classes 
class MyThread extends Thread {
//2. rewrite Thread Class run Method --> Declare the operation performed by this thread in run() in
@Override
public void run() {
// The function of this thread
}
} public class ThreadTest {
public static void main(String[] args) {
//3. establish Thread Object of subclass of class
MyThread t1 = new MyThread();
//4. Call... Through objects start Method
t1.sart();
}
}
  • Be careful :

    • You can't call... Directly run() Start the thread in the same way ( It's essentially just a method call , Single thread )
    • Do not let the thread being started execute any code ( Report errors IllegalThreadException). You need to recreate a new thread object .

Mode two : Realization Runnable Interface

  1. Create an implementation Runnable The class of the interface

  2. Implement classes to implement Runnable Abstract methods in :run()

  3. Create objects that implement classes

  4. Pass this object as an argument to Thread In the constructor of class , establish Thread Class object

  5. adopt Thread Class object call start()

    ( It's actually calling theta Runnable Type of target)

    Example :

    //1, Create an implementation Runnable The class of the interface 
    class Mthread implements Runnable {
    @Override
    public void run() {
    //2. rewrite Runnable Abstract methods in run()
    }
    } public class ThreadTest1 {
    public static void main(String[] args) {
    //3. Create objects that implement classes
    MThread mThread = new MThread();
    //4. Pass the object as a parameter to Thread In the constructor of class , establish Thread Class object
    Thread t1 = new Thread(mThread);
    //5, adopt Thread Class object call start()
    t1.start();
    }
    }

A comparison of the two ways

  1. Priority in development : Realization Runnable How to interface

    reason :

    1. The way of implementation is not limited by the single inheritance of class
    2. The implementation method is more suitable to deal with the situation that multiple threads have shared data
  2. Actually Thread The class itself inherits Runnable Interface , And built in the rewritten run().

Two 、Thread Class

  • void start() : Start thread , And execute the object's run() Method
  • run() : It usually needs to be rewritten Thread Class , Declare the operation to be performed by the created thread in this method
  • String getName() : Returns the name of the thread
  • void setName(String name) : Set the thread name
  • static Thread.currentThread() : Returns the current thread . stay Thread In subclasses this, It is usually used for the main thread and Runnable Implementation class
  • yield() : Release the current cpu The enforcement of
  • join() : In a thread a Calling thread b The thread of join(), The thread a Go into blocking mode , Until the thread b After full implementation , Threads a To end the blocking .
  • stop() : Deprecated . Force end of current thread .
  • sleep(long millitime) : Make the current thread “ sleep ” Fixed value millitime millisecond . At the designated millitime In milliseconds , The current thread is blocked .
  • isAlive() : Determine whether the current thread is alive ( The return value is boolean)

3、 ... and 、 Scheduling of threads

1. Dispatch

  • Scheduling strategy

    • Time slice :
    • Preemptive : High priority thread preemption CPU
  • Java The scheduling method of
    • Threads of the same priority form a first in first out queue ( First come, first serve ), Using time slice strategy
    • For high priority , Preemptive strategy using priority scheduling

2. Thread priority

  • The default configuration :

    • MAX_PRIORITY:10
    • MIN_PRIORITY:1
    • NORM_PRIORITY:5
  • Set operation

    • Thread object name .getPriority()

      Get thread priority

    • Thread object name .setPriority()

      Set thread priority

  • Priority understanding

    High priority threads should preempt low priority threads cpu The enforcement of . But just in terms of probability , High priority threads are executed with high probability . It doesn't mean that only when the high priority thread finishes executing , Low priority threads only execute

Java Multithreading basics notes ( Continuous updating ) More articles about

  1. Java Multithreading —— Basic knowledge of

    java Multithreading Catalog : Java Multithreading —— Basic knowledge of Java Multithreading —— synchronized keyword java Multithreading —— An example of timing scheduling java Multithreading ——quartz An example of timing scheduling ...

  2. Java Summary of basic knowledge of multithreading

    2016-07-18 15:40:51 Java  Multithreading Foundation 1.  Threads and processes 1.1  Process concept Process is the basic unit of resource allocation , It is also the basic unit of dispatching operation . for example , Users run their own programs , The system creates a process , ...

  3. Java Multithreading basics summary notes

    This note records some of the information in Java Common keywords in multithreaded programming , It's relatively simple and basic. I don't write it in too much detail . One .Thread class ( In fact, it is also applied Runnable Interface ) and Runnable Interface ( only one run Method , The application of this class must be ...

  4. Java Basic knowledge of multithreading

    This article is Java A summary of the basic usage of multithreading . This article will explain from the following aspects Java Basic usage of multithreading : How to use multithreading How to get some information about multithreading How to stop a thread How to pause a thread Some other uses of threads All the code ...

  5. JAVA Multithreading Basics ( One )

    One . Basic knowledge of To understand multithreading, you need to know some necessary concepts , Like the process , Threads, etc. . Developing multithreaded programs is conducive to making full use of system resources (CPU resources ), Make your program run faster , More timely response . 1. process , It generally refers to the execution of a program or task ...

  6. Database and SQL Basic knowledge of interview questions ( Continuous updating )

    Review the basic knowledge of database Always ask small questions : One .like Query case problems : sql Query result de duplication  SELECT distinct name FROM surface : The average avg One .like Query case problems : ① use bina ...

  7. Java Examples of multithreading Basics

    One . management 1. Create thread Thread public class Main { public static void main(String[] args) { MyThread myThread = ...

  8. Java Multithreading Basics ( Two )

    One . Java Threads have 6 States  NEW The initial state , Thread created , But not yet called start Method . RUNNABLE Running state ,java Threads refer to the ready and running states of the operating system as in progress . BLOCKE ...

  9. Java Basic knowledge of ( Ongoing update ...)

    1. Member variables : Global variables / Field (Field), Don't call it an attribute ( error ) Directly defined in a class , Method outside 1. Class member variable     Use static Decorated variable 2. Instance member variable No use static Decorated variable local variable ...

  10. Java Multithreading - Basic knowledge of

    One . A process is an executing program , The program is static ( We don't run it after we've written it, we keep it there ), A process is an executing program , It's a dynamic concept . A process can have multiple threads . Two . Multithreading consists of two or more concurrent parts , Put each one in the program like this and ...

Random recommendation

  1. Apache2.4 Deploy django appear 403 Forbidden Error resolution

    Preface :Apache2.4 Deploy django appear 403 Forbidden It's better to combine mistakes with apache In the error log to see what kind of errors cause 403 error In the afternoon, baidu didn't find a solution , Tried. n Methods , It's like a fool ...

  2. HDU 5119

    A problem forced by a senior ... Thank him ~   In question dp[i][j] i That is the second i Number ,j For the number currently entered, you can xor It's the number that you get At the same time, a number has two choices ,1.not xor  2.xor maximal j Not more than 11...11b( ...

  3. DotNetBar v12.5.0.2 Fully Cracked

    Update the information : http://www.devcomponents.com/customeronly/releasenotes.asp?p=dnbwf&v=12.5.0.2 If you have a problem with cracking, please contact me ...

  4. self-taught spring Problems encountered in the process list, One by one

    1.spring The basic principle of 2.spring There are several ways to annotate 3. What kind of annotation is appropriate under what circumstances 4.@autowired @Resource And so on 5.spring How reflection is used 6.cjlibe ...

  5. mapper.xml How to achieve Dao Layer interface

    I wrote a simple story in the morning from xml Reading information instantiates a Bean object . I started thinking in the afternoon mybatis How to get through xml File to implement dao Layer interface , I wanted to use it directly at first Class.forName(String name) Then tune up ...

  6. eclipse Quick annotation generation method

    Automatically generate annotation formats for methods , for example /*** @param str* @return* @throws ParseException*/ Shortcut keys are alt+shift+j, Place the cursor over the method name , Press shortcut key . Will generate ...

  7. Windows Open file

    cmd in , windows   Open file command :start: Linux       Open file command :open

  8. Access modifier (C# Programming Guide )

    All types and type members have accessibility levels , This level controls whether they can be used from your assembly or from other code in other assemblies .  You can use the following access modifiers to specify the accessibility of a type or member when making a declaration : public Any... In the same assembly ...

  9. 【MySQL】MySQL Supported data types

    1. integer MySQL data type meaning ( A signed ) tinyint(m) 1 Bytes Range (-128~127) smallint(m) 2 Bytes Range (-32768~32767) mediumint(m) 3 ...

  10. Java And I/O flow ( The first 2 part )

    1.  Node class type : 2.  access files : Demo_1: import java.io.FileInputStream; import java.io.FileNotFoundException; imp ...