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

1、 Introduction to concurrent programming

1. Basic concepts

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

A process is a program in a computer. It is a running activity on a data set. It is the basic unit for resource allocation and scheduling of the system and the basis of the structure of the operating system. In the early computer structure of process oriented design, process is the basic executive entity of program; In thread oriented computer architecture, a process is a container for threads. Program is the description of instructions, data and their organizational form, and process is the entity of program.

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

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

Multiple tasks are processed "simultaneously" on one processor, and complex and time-consuming tasks in programs are processed in parallel. Concurrency is multiple events on the same entity. Multiple events occur at the same time interval.

2. Introductory case

@H_502_41@public class HelloThread {
    public static void main(String[] args) {
        System.out.println("Hello,Thread");
        // 当前线程名称
        System.out.println(Thread.currentThread().getName());
        // 线程系统的管理接口
        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 more than one main thread is executing the above simple java program.

2、 Thread creation method

1. Inherit thread class

Infrastructure of thread class:

@H_502_41@class Thread implements Runnable

The runnable interface has been implemented here.

@H_502_41@public class CreateThread01 {
    public static void main(String[] args) {
        // 调用方法
        MyThread1 myThread1 = new MyThread1() ;
        myThread1.start();
    }
}
class MyThread1 extends Thread {
    // 设置线程名称
    public MyThread1 (){
        super("CicadaThread");
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

2. Implement 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. At this time, you can implement the runnable interface.

@H_502_41@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

Define a class in a class, which is called an inner class. The inner class is equivalent to a member of the outer class, and the inner class can be regarded as a whole.

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

        //方式2
        new Thread(new Runnable() {
            public void run() {
                System.out.println("2:"+Thread.currentThread().getName());
            }
        },"ThreadName2"){
            // 这里重写了run方法
            @Override
            public void run() {
                System.out.println("3:"+Thread.currentThread().getName());
            }
        }.start();
    }
}

4. Return value thread

As the name suggests, after the thread executes asynchronously, it can return the processing result of the thread.

@H_502_41@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();
        // 等待获取结果
        // Integer result = task.get();
        // 设置获取结果的等待时间,超时抛出:TimeoutException
        Integer result = task.get(3,TimeUnit.SECONDS) ;
        System.out.println("result="+result);
    }
}
class MyThread4 implements Callable<Integer> {
    // 封装线程执行的任务
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(1000);
        return 2+3;
    }
}

5. Timed task

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

@H_502_41@class TimerTask implements Runnable

Task class: the TimerTask structure implements the runnable interface.

@H_502_41@public class CreateThread05 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("延迟1s,每隔3s执行一次");
            }
        },1000,3000);
    }
}

6. Thread pool management

Thread pool is a form of multi-threaded processing. Tasks are added to the queue during processing, and then automatically started after threads are created.

@H_502_41@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. State description

Initial state: after building the thread instance, the start () method is activated before it is activated.

Running state: in Java threads, the ready and running states are called running states. In the actual execution process, the two states can be switched at any time. When the start () method is called, or after sleep (), the join () ends, it enters the runnable ready state and starts waiting for the CPU time slice; Thread scheduling: after the thread is selected and the CPU time slice is allocated, the thread is running even though it is in the runnable state;

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

Wait state: a thread that enters this state, waiting to be notified or interrupted by other threads, also known as explicit wake-up.

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

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

2. Case process analysis

@H_502_41@public class StateCycle01 {
    public static void main(String[] args) throws Exception {
        // 进入初始状态
        StateThread01 stateThread01 = new StateThread01();
        FutureTask<String> task = new FutureTask<>(stateThread01);
        Thread thread = new Thread(task,"GetValueThread");
        // 运行状态
        thread.start();
        // 超时等待结果
        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 {
        // 超时等待
        Thread.sleep(1000);
        return "Hello,Cicada";
    }
}
class StateThread02 implements Runnable {
    @Override
    public void run() {
        synchronized (StateCycle01.class) {
            System.out.println("进入线程...");
            try {
                // 等待状态,放弃对象锁
                StateCycle01.class.wait(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("线程继续...");
        }
    }
}

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

The description of the thread state is not complicated, but the switching between each state is very complex. It will be explained separately in modules.

4、 Summary of advantages and disadvantages

1. Advantage description

The most direct effect greatly improves the efficiency of program execution; The program is asynchronously decoupled. In web development, there are often follow-up programs to be executed, and there is a need for fast 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 for multithreads to compete for resources; It is not that the more threads, the faster the execution speed. Switching before threads is time-consuming, so it is necessary to reasonably create and use the lock mechanism; Thread creation and communication need clear logic; Thread deadlock is an unavoidable problem; Therefore, in general, the company's specifications for thread use are very strict.

5、 Source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>