Concurrent Programming Notes

Keywords: Java Back-end computer language

Content overview

What is multithreading, synchronous asynchronous concept, thread safety (synchronization between threads), communication between threads, JDK1.8 parallel contracting, thread pool principle analysis, lock
1. Thread: an execution path that does not interfere with each other.
It is divided into user thread and daemon thread.
It can also be divided into: main thread, sub thread and GC thread. In a process, there must be a main thread.
2. Multithreading: in a process, multiple execution paths are executed at the same time, in order to improve efficiency

1 Fundamentals of concurrent programming

1.1 creating threads

1.1.1 inherit Thread class

Inherit Thread and override run method

public class ThreadDemo01 extends Thread{

    public static void main(String arg[]){
        System.out.println("-----Main thread start-----");
        //Create thread
        ThreadDemo01 threadDemo01 = new ThreadDemo01 ();
        //Start thread
        threadDemo01.start();
        for(int i = 10; i > 0; i--){
            System.out.println("Main thread" + i);
        }
        System.out.println("-----Main thread end-----");
    }

    @Override
    public void run() {
        for(int i = 10; i > 0; i--){
            System.out.println("Child thread" + i);
        }
    }
}

1.1.2 implement the Runnable interface and rewrite the run method

/**
 * Implement the Runnable interface and rewrite the run method
 */
public class ThreadDemo02 implements Runnable{

	public static void main(String arg[]){
		System.out.println("-----Main thread start-----");
		//Create thread
		ThreadDemo02 threadDemo02 = new ThreadDemo02 ();
		//Start thread
		Thread t = new Thread(threadDemo02);
		t.start();
		for(int i = 10; i > 0; i--){
			System.out.println("Main thread" + i);
		}
		System.out.println("-----Main thread end-----");
	}

	@Override
	public void run() {
		for(int i = 10; i > 0; i--){
			System.out.println("Child thread" + i);
		}
	}
}

1.1.3 anonymous inner class

public class ThreadDemo03 {
    public static void main(String[] args) {
        System.out.println("-----Main thread start-----");
        new Thread(new Runnable(){
            @Override
            public void run() {
                for(int i = 10; i > 0; i--){
                    System.out.println("Child thread" + i);
                }
            }
        }).start();
        for(int i = 10; i > 0; i--){
            System.out.println("Main thread" + i);
        }

        System.out.println("-----Main thread end-----");
    }
}

1.2 five states of multithreading

  1. New status: new Thread()
  2. Ready status: wait for CPU to allocate memory and execute
  3. Running status: execute run()
  4. Death status: run() completed
  5. Blocking state: the run() method calls wait(), sleep() or thread lock blocking state, and returns to the ready state after execution.

1.3 daemon thread

  • Main thread: a process has and only has one main thread.
  • User thread: a thread created by a user, not a daemon thread. If the main thread finishes executing, the user thread will not be affected.
  • GC thread: the garbage in the heap is collected from time to time, and the daemon thread is destroyed together with the main thread.

The daemon thread is destroyed together with the main thread.

public class TreadDemo implements Runnable{
    public static void main(String arg[]){
        System.out.println("-----Main thread start-----");
        //Create thread
        TreadDemo treadDemo = new TreadDemo();
        //Start thread
        Thread t = new Thread(treadDemo);
        t.setDaemon(true); //Set as daemon thread
        t.start();
        for(int i = 100; i > 0; i--){
            System.out.println("Main thread" + i);
        }
        System.out.println("-----Main thread end-----");
    }

    @Override
    public void run() {
        for(int i = 100; i > 0; i--){
            System.out.println("Child thread" + i);
        }

    }
}

1.4 join() method

During the execution of A thread, the B thread's join method is invoked. A will wait for the execution of join, and then continue execution.
The join() method is to release the CPU execution rights of other threads to join.

public class TreadDemo{
    public static void main(String arg[]){
        System.out.println("-----Main thread start-----");

        //Start thread
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 10; i > 0; i--){
                    System.out.println("Child thread" + i);
                }
            }
        });
        t.start();
        try {
            t.join(); //Cede the execution right of the CPU to the child thread
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 10; i > 0; i--){
            System.out.println("Main thread" + i);
        }
        System.out.println("-----Main thread end-----");
    }
}


Question: among the three threads T1, T2 and T3, how to ensure that T2 executes after T1 and T3 executes after T2?

public class TreadDemo{
    public static void main(String arg[]){
        System.out.println("-----T3 Thread start-----");

        //Start thread
        Thread T2 = new Thread(new Runnable() {
            @Override
            public void run() {
                //Start thread
                Thread T1 = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        for(int i = 3; i > 0; i--){
                            System.out.println("T1 thread " + i);
                        }
                    }
                });
                T1.start();
                try {
                    T1.join(); //Cede the execution right of the CPU to the child thread
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int i = 3; i > 0; i--){
                    System.out.println("T2 thread " + i);
                }
            }
        });
        T2.start();
        try {
            T2.join(); //Cede the execution right of the CPU to the child thread
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 3; i > 0; i--){
            System.out.println("T3 thread " + i);
        }
        System.out.println("-----T3 Thread end-----");
    }
}

2 thread safety

Distributed lock: built-in lock and display lock
Built in lock (interlock): synchronized
Display Lock: Lock

Thread synchronization, pay attention to deadlock (for example, synchronization nested synchronization)
threwLocal: provides local variables for threads
Three characteristics: atomicity, visibility and ordering (code execution order, jvm reordering in multithreading)
JVM memory model

2.1 what is thread safety

Thread safety: when multiple threads share a global variable for write operations, they may be affected by other threads. Read operations do not cause thread safety problems. For example, multiple windows sell train tickets.

public class TreadDemo implements Runnable{

    //Multiple windows sell 100 train tickets at the same time
    private int count=100;

    @Override
    public void run() {
        while(count > 0){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sale();
        }
    }

    private void sale(){
        if(count > 0){
            System.out.println(Thread.currentThread().getName() + ": The second is being sold"+(100-count+1) + "A train ticket");
            count--;
        }
    }
}

class test{
    public static void main(String[] arg){
        TreadDemo td = new TreadDemo();
        Thread t1 = new Thread(td,"Thread 1");
        Thread t2 = new Thread(td,"Thread 2");
        t1.start();
        t2.start();
    }
}


Solution: add synchronized in the method of operating shared parameters. The smaller the synchronization range, the better.

    private synchronized void sale(){
        if(count > 0){
            System.out.println(Thread.currentThread().getName() + ": The second is being sold"+(100-count+1) + "A train ticket");
            count--;
        }
    }

synchronized, pessimistic lock. When a thread enters a method, it automatically obtains the lock and other threads wait. When the thread is executed, the lock is released to reduce the running efficiency of the program. Synchronization method, synchronization code block.

  1. Synchronous code block
    Synchronized (global variable) {}

We have expanded some functions and syntax support for the Markdown editor. In addition to the standard Markdown editor functions, we have added the following new functions to help you blog with it:

  1. The new interface design will bring a new writing experience;
  2. Set your favorite code highlight style in the creation center, and Markdown will display the selected highlight style of code slice display;
  3. The picture drag function is added. You can drag local pictures directly to the editing area for direct display;
  4. New KaTeX mathematical formula syntax;
  5. Added mermaid syntax supporting Gantt chart 1 Function;
  6. The function of multi screen editing Markdown article is added;
  7. Functions such as focus writing mode, preview mode, concise writing mode and synchronous wheel setting in left and right areas are added. The function button is located between the editing area and preview area;
  8. Added check list function.

Function shortcut

Undo: Ctrl/Command + Z
Redo: Ctrl/Command + Y
Bold: Ctrl/Command + B
Italic: Ctrl/Command + I
Title: Ctrl/Command + Shift + H
Unordered list: Ctrl/Command + Shift + U
Ordered list: Ctrl/Command + Shift + O
Checklist: Ctrl/Command + Shift + C
Insert code: Ctrl/Command + Shift + K
Insert link: Ctrl/Command + Shift + L
Insert picture: Ctrl/Command + Shift + G
Find: Ctrl/Command + F
Replace: Ctrl/Command + G

Creating a reasonable title is helpful to the generation of the directory

Directly input once #, and press space to generate level 1 title.
After entering twice #, and pressing space, a level 2 title will be generated.
By analogy, we support level 6 titles. It helps to generate a perfect directory after using TOC syntax.

How to change the style of text

Emphasize text emphasize text

Bold text bold text

Tag text

Delete text

Reference text

H2O is a liquid.

210 the result is 1024

Insert links and pictures

Link: link.

Picture:

Pictures with dimensions:

Centered picture:

Centered and sized picture:

Of course, in order to make users more convenient, we have added the image drag function.

How to insert a beautiful piece of code

go Blog settings Page, select a code slice highlighting style you like, and the same highlighted code slice is shown below

// An highlighted block
var foo = 'bar';

Generate a list that suits you

  • project
    • project
      • project
  1. Item 1
  2. Item 2
  3. Item 3
  • Planning tasks
  • Complete the task

Create a table

A simple table is created as follows:

projectValue
computer$1600
mobile phone$12
catheter$1

The setting content is centered, left and right

Use: ---------: Center
Use: --------- left
Usage -----------: right

First columnSecond columnThird column
First column text centeredThe text in the second column is on the rightThe text in the third column is left

SmartyPants

SmartyPants converts ASCII punctuation characters to "smart" printed punctuation HTML entities. For example:

TYPEASCIIHTML
Single backticks'Isn't this fun?''Isn't this fun?'
Quotes"Isn't this fun?""Isn't this fun?"
Dashes-- is en-dash, --- is em-dash– is en-dash, — is em-dash

Create a custom list

Markdown Text-to- HTML conversion tool Authors John Luke

How to create a footnote

A text with footnotes. 2

Annotations are also essential

Markdown converts text to HTML.

KaTeX mathematical formula

You can render LaTeX mathematical expressions using KaTeX:

Gamma formula display Γ ( n ) = ( n − 1 ) ! ∀ n ∈ N \Gamma(n) = (n-1)!\quad\forall n\in\mathbb N Γ (n)=(n−1)! ∀ N ∈ N is through Euler integral

Γ ( z ) = ∫ 0 ∞ t z − 1 e − t d t   . \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. Γ(z)=∫0∞​tz−1e−tdt.

You can find more information about LaTeX mathematical expressions here.

New Gantt chart features to enrich your articles

  • For Gantt chart syntax, refer to here,

UML diagram

UML diagrams can be used for rendering. Mermaid For example, a sequence diagram is generated as follows:

This will produce a flowchart.:

  • For Mermaid syntax, see here,

FLowchart

We will still support the flowchart of flowchart:

  • For Flowchart syntax, refer to here.

Export and import

export

If you want to try this editor, you can edit it at will in this article. When you have finished writing an article, find the article export in the upper toolbar and generate a. md file or. html file for local saving.

Import

If you want to load an. md file you have written, you can select the import function in the upper toolbar to import the file with the corresponding extension,
Continue your creation.

  1. mermaid syntax description ↩︎

  2. Explanation of footnotes ↩︎

Posted by spaceknop on Mon, 08 Nov 2021 02:08:46 -0800