This article source: making here | | GitEE, click here

Introduction to concurrent programming

1. Basic concepts

  • The program

Computer programs, procedures, rules and possible documents, documents, and data relating to the operation of a computer system.

  • process

Process is a computer program, about a data set on a running activity, the system is the basic unit of resource allocation and scheduling, is the basis of the operating system structure. In the early process-oriented computer architecture, the process is the basic execution entity of the program. In a thread-oriented computer architecture, a process is a container for threads. A program is a description of instructions, data and their organizational form, while a process is an entity of the program.

  • thread

Thread is the smallest unit that the operating system can schedule operations. It is contained in the process and is the actual operating unit in the process. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel.

  • Sequential programming

All steps in a program can perform only one step at any time. Most scenarios in programming are sequential programming.

  • Concurrent programming

Processing multiple tasks “simultaneously” on a single processor, in parallel with complex, time-consuming tasks in a program. Concurrency is multiple events on the same entity. Multiple events occur at the same time interval.

2. Introductory cases

public class HelloThread {
    public static void main(String[] args) {
        System.out.println("Hello,Thread");
        // The current thread name
        System.out.println(Thread.currentThread().getName());
        // The management interface of the thread system
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] threadIds = threadMXBean.getAllThreadIds() ;
        for (long id : threadIds) {
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(id) ;
            System.out.println(threadInfo.getThreadId()+
                    ":"+threadInfo.getThreadName()); }}}Copy the code

Print result:

5:Monitor Ctrl-Break
4:Signal Dispatcher
3:Finalizer
2:Reference Handler
1:main
Copy the code

This shows that there is more than one main thread executing a simple Java program.

Second, thread creation method

Inherit the Thread class

The infrastructure of the Thread class:

class Thread implements Runnable
Copy the code

The Runnable interface is already implemented here.

public class CreateThread01 {
    public static void main(String[] args) {
        // Call the method
        MyThread1 myThread1 = newMyThread1() ; myThread1.start(); }}class MyThread1 extends Thread {
    // Set the thread name
    public MyThread1 (a){
        super("CicadaThread");
    }
    @Override
    public void run(a) { System.out.println(Thread.currentThread().getName()); }}Copy the code

2. Implement Runnable interface

If you create a Thread class that already has a parent class, you can no longer inherit the Thread class. Multiple inheritance is not allowed in Java, so you can implement the Runnable interface.

public class CreateThread02 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread2(),"MyThread2"); thread.start(); }}class MyThread2 implements Runnable {
    @Override
    public void run(a) {
        System.out.println(Thread.currentThread().getName()+" run ..."); }}Copy the code

Anonymous inner classes

Defines a class within a class, called an inner class. An inner class is a member of an outer class and can be considered as a whole.

public class CreateThread03 {
    public static void main(String[] args) {
        1 / / way
        new Thread("ThreadName1") {
            public void run(a) {
                System.out.println("1:"+Thread.currentThread().getName());
            };
        }.start();

        2 / / way
        new Thread(new Runnable() {
            public void run(a) {
                System.out.println("2:"+Thread.currentThread().getName()); }},"ThreadName2") {// This overrides the run method
            @Override
            public void run(a) {
                System.out.println("3:"+Thread.currentThread().getName()); } }.start(); }}Copy the code

4. Return value thread

As the name implies, this thread thread asynchronously executes, can return the thread’s processing results.

public class CreateThread04 {
    public static void main(String[] args) throws Exception {
        MyThread4 myThread4 = new MyThread4();
        FutureTask<Integer> task = new FutureTask<>(myThread4);
        Thread thread = new Thread(task,"TaskThread");
        thread.start();
        // Wait for the result
        // Integer result = task.get();
        // Set the time to wait for the result
        Integer result = task.get(3, TimeUnit.SECONDS) ;
        System.out.println("result="+result); }}class MyThread4 implements Callable<Integer> {
    // Encapsulates the tasks performed by the thread
    @Override
    public Integer call(a) throws Exception {
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(1000);
        return 2+3; }}Copy the code

5. Scheduled tasks

Timer is a tool class for background threads to perform task scheduling. It can be periodically or repeatedly executed according to rules.

class TimerTask implements Runnable
Copy the code

Task class: The TimerTask structure implements the Runnable interface.

public class CreateThread05 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run(a) {
                System.out.println("Delay 1s, execute every 3s."); }},1000.3000); }}Copy the code

6. Thread pool management

Thread pooling is a form of multithreaded processing in which tasks are added to a queue and then automatically started after a thread is created.

public class CreateThread06 {
    public static void main(String[] args) {
        Executor threadPool = Executors.newFixedThreadPool(5);
        for(int i = 0; i <5 ; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run(a) { System.out.println(Thread.currentThread().getName()); }}); }}}Copy the code

Third, thread state management

1. State description

  • NEW

Initial state: In this state after a thread instance is built and before it is started by calling the start() method.

  • RUNNABLE

Running state: In Java threads, the ready and running states are called running states, and these two states can be switched at any time during actual execution. When the start() method is called, or after sleep(), join() is finished, etc., it enters the RUNNABLE state and waits for the CPU time chip. Thread scheduling After the thread is selected and the CPU time slice is allocated, the thread is in the Runnable state, which is Running.

  • BLOCKED

Blocked: Usually blocked by a locking mechanism, indicating that the thread is acquiring a resource controlled by a lock.

  • WAITING

Wait state: A thread that enters this state and waits to be notified or interrupted by another thread, also known as explicit wake up.

  • TIMED_WAITING

Timeout wait state: This state is different from WAITING state, the thread in this state can automatically wake up after a specified time;

  • TERMINATED

Terminated: The current thread task is completed.

2. Case process analysis

public class StateCycle01 {
    public static void main(String[] args) throws Exception {
        // Enter the initial state
        StateThread01 stateThread01 = new StateThread01();
        FutureTask<String> task = new FutureTask<>(stateThread01);
        Thread thread = new Thread(task,"GetValueThread");
        // Running status
        thread.start();
        // Time out to wait for results
        String result = task.get(3, TimeUnit.SECONDS) ;
        System.out.println("result="+result);

        StateThread02 stateThread02 = new StateThread02() ;
        Thread thread1 = new Thread(stateThread02,"WaitThread"); thread1.start(); }}class StateThread01 implements Callable<String> {
    @Override
    public String call(a) throws Exception {
        // Wait for timeout
        Thread.sleep(1000);
        return "Hello,Cicada"; }}class StateThread02 implements Runnable {
    @Override
    public void run(a) {
        synchronized (StateCycle01.class) {
            System.out.println("Enter thread...");
            try {
                // The object lock is abandoned
                StateCycle01.class.wait(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Thread continues..."); }}}Copy the code

The above process describes the switch between different thread states. The basic flow chart is as follows.

Thread states are not complicated to describe, but switching between each state is very complex and will be explained separately in modules later.

4. Summarize the advantages and disadvantages

1. Advantages

The most direct effect to greatly improve the efficiency of program execution; Program asynchronous decoupling, in web development, there are often follow-up programs to execute, there is a need for fast user interface response; Of course, skilled use of concurrent programming, is also a good programmer skills.

2. Disadvantage analysis

The learning curve of concurrent programming is very steep and difficult; It is easy to have problems when competing for resources between multiple threads. It is not that the more threads, the faster the execution speed, the thread before switching is time-consuming, need to create and use a reasonable lock mechanism; Thread creation and communication needs very clear logic; Thread deadlock is an unavoidable problem. So in general companies are very strict about the specifications they use for threads.

Five, source code address

Making address GitEE, https://github.com/cicadasmile/java-base-parent, https://gitee.com/cicadasmile/java-base-parentCopy the code