Home  >  Article  >  Java  >  Java asynchronous task implementation and analysis

Java asynchronous task implementation and analysis

PHPz
PHPzforward
2023-04-22 20:49:061473browse

1. What is an asynchronous task

Whether it is in life or in a program, it can be roughly divided into two types: synchronous and asynchronous.

Synchronization: For example, if you go to eat Haidilao, you have to order the bottom of the pot first, then the dishes, then the waiter brings the bottom of the pot, then the dishes, and finally you can eat the dishes. This process must be done in order. .

Asynchronous tasks: Let’s go eat Haidilao. There are many people eating. There are many people in front of you. You may have to queue up and wait until you are in line before you can enter the restaurant. But what if you want to go to the toilet halfway? You have to queue up again when you come back. So there is a call system. You queue up to get a number first, and then you can go get a massage, watch a movie, go to the spa, buy a cup of milk tea... It's finally your turn. At this time, you will be notified that you are in line, and then you can enter. This process is asynchronous.

2. SpringBoot Async

At first I thought about opening a thread pool and throwing the tasks into the thread pool to complete.

Later I remembered that SpringBoot has a more convenient asynchronous framework Async

The code is also very simple. You only need to add @Async to the method that needs asynchronous execution, and add @EnableAsync to the SpringBoot startup class. That’s it

    @Async
    public void task() {
        // do something
    }

3. Pitfall diary

Although the code is small, the pitfalls will not decrease as the amount of code decreases.

For the sake of convenience, I built a demo locally and directly uploaded the code

@RestController
public class AsyncController {
    @Autowired
    private AsyncService asyncService;

    @GetMapping("/v1/say")
    public String sayV1() {
        asyncService.sayV1();
        return "success1";
    }

    @GetMapping("/v2/say")
    public String sayV2() {
        asyncService.sayV2();
        return "success2";
    }
}
@Service
public class AsyncService {
    public void sayV1() {
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello world");
    }

    @Async
    public void sayV2() {
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello world");
    }
}

It is a very simple demo that provides two interfaces, /v1/say and /v2/say, one for synchronous execution , an asynchronous execution that simulates time-consuming tasks by sleeping for 3 seconds

Start normally without any problems. If it is executed synchronously, wait 3 seconds before the main thread will return. If it is executed asynchronously, it will return immediately and wait 3 seconds. Helloworld

will be output. However, when I added a breakpoint, a problem occurred.

I first added a breakpoint on the line that prints hello world. The effect is the same as the original one, except that it is blocked before printing, but it does not affect the return of the main thread.

Java asynchronous task implementation and analysis

Edit

But when I added a breakpoint where the method came in, I found that the main thread was actually blocked!

Java asynchronous task implementation and analysis

Edit

4. Solve

Various problem solving, @Async does not take effect, asynchronous tasks wait for the main thread to return, nothing happens Find effective solutions.

Later, a colleague reminded me, could it be a thread blocked by the debug function?

With the attitude of giving it a try, I found the debug configuration

Java asynchronous task implementation and analysis

Edit

The breakpoint can choose to block the jvm Or block the current thread. The default is to block the jvm.

Select suspend to Thread, and the main thread will no longer be blocked

The above is the detailed content of Java asynchronous task implementation and analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete