5

Preface

My requirement is to create a new thread to perform some operations, because if the same thread is used, resources will be occupied all the time, affecting response efficiency.

Asynchronous concept

my understanding: asynchronous shall be in multiple vehicles traveling on a road in multiple, simultaneous multiple vehicles travel that is in a way. give a chestnut: synchronization: If you are currently learning C language, then we should not learn C++ according to the course schedule. Only after the end of this semester, we can learn C++ in the next semester. Asynchronous: Discrete mathematics and c language are both studied in this semester, you don't have to wait for the c language to finish learning discrete mathematics.

How does spring boot implement asynchronous

Google search found that there are asynchronous annotations.
image.png

How To Do @Async in Spring

image.png
image.png
image.png
image.png

@Async
public void asyncMethodWithVoidReturnType() {
    System.out.println("Execute method asynchronously. " 
      + Thread.currentThread().getName());
}

: 1. Enable asynchronous support 2. Note on the use of asynchronous annotation 3. Asynchronous example

My asynchronous stepping hole

1. Did not read two limitations carefully: Self-invocation — won't work.

test code for

public class AsyncTest {
  @Test
  public void test1() {
    System.out.println("test1的线程id为:" + Thread.currentThread().getId());
    test2();
  }
  
  @Async
  public void test2() {
    System.out.println("test2的线程id为:" + Thread.currentThread().getId());
  }
}

effect: are the same thread, which does not achieve the effect of test2 being a separate thread
image.png
Solution: Put test2 in another class, self-invoking will not take effect.

2. Must be @Component or @Service annotation to make @Async effective

Putting asynchronous methods into other classes:

// 第一个类
public class AsyncTest1 {
  public void test1() {
    System.out.println("test1的线程id为:" + Thread.currentThread().getId());
    // 新建一个AsyncTest2类,调用其异步方法
    AsyncTest2 asyncTest2 = new AsyncTest2();
    asyncTest2.test2();
  }
}

// 第二个类,定义异步方法
public class AsyncTest2 {
  @Async
  public void test2() {
    System.out.println("test2的线程id为:" + 
        Thread.currentThread().getId());
  }
}

But: The result is not what I want, the print display is still the same thread.

solve:

Spring creates a proxy for each service and component you create using the common annotations. Only those proxies contain the wanted behavior defined by the method annotations such as the Async. So, calling those method not via the proxy but by the original naked class would not trigger those behaviors.
In short: Spring will @Component and @ Service . Only classes with proxies can get the desired results when @Async


郝泽龙_HZ
182 声望2 粉丝