Java Concurrent Programming (01): thread creation, state cycle management

Keywords: Java Programming github Web Development

Source code: GitHub point here || GitEE point here

1, Introduction to concurrent programming

1. Basic concepts

  • program

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

  • process

A process is a program in a computer. A running activity on a data set is the basic unit of resource allocation and scheduling of the system and the basis of the operating system structure. In the early process oriented computer structure, the process is the basic execution entity of the program; in the thread oriented computer structure, the process is the container of the thread. A program is a description of instructions, data and their organizational forms. A process is an entity of a program.

  • thread

Thread is the smallest unit that the operating system can schedule operations. It is included in the process and the actual operation unit of the process. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process. Each thread performs different tasks in parallel.

  • Sequential programming

All steps in a program can only execute one step at any time. Most of the programming scenarios are based on sequential programming.

  • Concurrent programming

Processing multiple tasks on one processor at the same time, which is a complex and time-consuming task in parallel processing program. Concurrency is multiple events on the same entity. Multiple events occur at the same time interval.

2. Entry case

public class HelloThread {
    public static void main(String[] args) {
        System.out.println("Hello,Thread");
        // Current thread name
        System.out.println(Thread.currentThread().getName());
        // Management interface of 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());
        }
    }
}

Print results:

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

It can be seen that the above simple Java program is executed by more than one main thread.

2, Thread creation method

1. Inherit Thread class

Infrastructure of Thread class:

class Thread implements Runnable

The Runnable interface has been implemented here.

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

2. Implement the Runnable interface

If the created Thread class already has a parent class, you can no longer inherit the Thread class. Multiple inheritance is not allowed in Java. Then 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() {
        System.out.println(Thread.currentThread().getName()+" run ...");
    }
}

3. Anonymous inner class

Defining a class within a class is called an inner class. Inner class is equivalent to a member of outer class, which can be regarded as a whole.

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

        //Mode 2
        new Thread(new Runnable() {
            public void run() {
                System.out.println("2:"+Thread.currentThread().getName());
            }
        },"ThreadName2"){
            // The run method is rewritten here
            @Override
            public void run() {
                System.out.println("3:"+Thread.currentThread().getName());
            }
        }.start();
    }
}

4. Return value thread

As the name implies, after asynchronous execution of the thread, the processing result of the thread can be returned.

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();
        // Waiting for results
        // Integer result = task.get();
        // Set the waiting time to get the result, timeout throw: TimeoutException
        Integer result = task.get(3, TimeUnit.SECONDS) ;
        System.out.println("result="+result);
    }
}
class MyThread4 implements Callable<Integer> {
    // Encapsulate tasks performed by threads
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(1000);
        return 2+3;
    }
}

5. Scheduled tasks

Timer is a tool class for background threads to execute task scheduling. It can be executed regularly or repeatedly according to rule configuration.

class TimerTask implements Runnable

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() {
                System.out.println("Delay 1 s,Every 3 s Execute once");
            }
        }, 1000, 3000);
    }
}

6. Thread pool management

Thread pool is a form of multithreading, in which tasks are added to the queue during processing, and then these tasks are automatically started after creating threads.

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() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }
}

3, Thread state management

1. Status description

  • NEW

Initial state: after the thread instance is built, it is in this state before the start() method is called.

  • RUNNABLE

Running state: in the Java thread, the ready and running states are called running states. In the actual execution process, these two states can be switched at any time. When the start() method is called, or after sleep(), the join() ends, etc., it enters the runnable ready state and begins to wait for the CPU time slice; when the thread is selected and allocated with the CPU time slice by the thread scheduling, the thread is in the runnable state, which is running state;

  • BLOCKED

Blocking status: usually refers to being blocked by the lock mechanism, indicating that the thread is acquiring resources under lock control.

  • WAITING

Waiting state: the thread entering this state, waiting to be notified or interrupted by other threads, also known as explicit wake-up.

  • TIMED_WAITING

Timeout WAITING state: this state is different from WAITING state. Threads in this state can wake up automatically after a specified time;

  • TERMINATED

Termination status: indicates that the current thread task has completed execution.

2. Case process analysis

public class StateCycle01 {
    public static void main(String[] args) throws Exception {
        // Enter initial state
        StateThread01 stateThread01 = new StateThread01();
        FutureTask<String> task = new FutureTask<>(stateThread01);
        Thread thread = new Thread(task,"GetValueThread");
        // running state
        thread.start();
        // Timeout waiting 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() throws Exception {
        // Timeout wait
        Thread.sleep(1000);
        return "Hello,Cicada";
    }
}
class StateThread02 implements Runnable {
    @Override
    public void run() {
        synchronized (StateCycle01.class) {
            System.out.println("Thread entry...");
            try {
                // Wait state, discard object lock
                StateCycle01.class.wait(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Thread continues...");
        }
    }
}

The above process describes the switch between different states of threads, and the basic flow chart is as follows.

The state description of a thread is not complicated, but the switch between each state is very complex, which will be explained in modules.

4, Summary of advantages and disadvantages

1. Advantages

The most direct role is to greatly improve the efficiency of program execution; program asynchronous decoupling, in web development, there are often follow-up programs to be executed, which need rapid user interface response; of course, skilled use of concurrent programming is also a necessary skill for an excellent programmer.

2. Defect analysis

The learning curve of concurrent programming is very steep and difficult; it is easy to have problems in competing for resources among multiple threads; it is not that the more threads, the faster the execution speed, the time-consuming before thread switching, and the lock mechanism needs to be reasonably created and used; the communication between thread creation and thread communication needs to be very clear logic; the thread deadlock problem can not be completely avoided; so in one In general, the company's specification for thread usage is very strict.

5, Source code address

GitHub·address
https://github.com/cicadasmile/java-base-parent
GitEE·address
https://gitee.com/cicadasmile/java-base-parent

Posted by pea on Wed, 04 Mar 2020 04:44:13 -0800