一、springboot中的异步任务
1、使用注解@Async创建一个可异步启动的方法
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class BeforeCall {
@SneakyThrows
@Async
public void asyncBefore() {
Thread.sleep(3000);
System.out.println("异步方法先调用但是后打印");
}
}
2、创建一个方便观察的普通方法
import org.springframework.stereotype.Service;
@Service
public class AfterCall {
public void afcall(){
System.out.println("普通方法,后调用但是先打印");
}
}
3、在一个方法中同时调用上面的方法
import com.cai.li.asynctask.service.AfterCall;
import com.cai.li.asynctask.service.BeforeCall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
@RequestMapping("/test")
public class DataController {
@Autowired
BeforeCall beforeCall;
@Autowired
AfterCall afterCall;
@RequestMapping("/asynctask")
public void test(){
beforeCall.asyncBefore();
afterCall.afcall();
}
}
4、在springboot启动类上加上注解@EnableAsync
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableAsync
public class AsynctaskApplication {
public static void main(String[] args) {
SpringApplication.run(AsynctaskApplication.class, args);
}
}
5、访问查看结果
二、一个线程获取另一个线程中值
1、新建一个类First,类实现Runable接口,在重写的run()方法中获取另一线程中的First类的属性name的值
import lombok.SneakyThrows;
public class First implements Runnable{
@SneakyThrows
@Override
public void run() {
Thread.sleep(5000);
Second first = new Second();
System.out.println("先调用但是后打印");
System.out.println("新线程"+Thread.currentThread().getName()+"获取的name:"+first.name);
}
}
2、新建一个类Second,类中的方法Data()负责给属性name赋值
public class Second {
//属性一定要加static变为静态属性,其他线程取值时才有数据,否则取到的就会是null
static String name;
public void Data(String data){
this.name = data;
System.out.println("后调用但是后打印");
System.out.println("线程"+Thread.currentThread().getName()+"中获取到的name:"+name);
}
}
3、新建一个测试的类
public class AsyncTetst {
public static void main(String[] args) {
First first = new First();
Second second = new Second();
new Thread(first).start();
second.Data("Lii");
}
}
4、运行后的结果