使用spring的异步任务创建线程

使用spring的异步任务创建线程

使用注解@Configuration配置上下文不在以以前的applictionContext.xml加载bean

@Configuration
@ComponentScan("com.ht")
@EnableAsync
public class Config {

}
@Component
public class Demo {


    @Async
    public void a() {
        while(true) {
            System.out.println("a");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Async
    public void b() {
        while(true) {
            System.out.println("b");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Main {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
        Demo demo = ctx.getBean(Demo.class);
        demo.a();
        demo.b();
    }
}

交替打印结果

a
b
b
a
b
a

你可能感兴趣的:(高并发)