springの非同期タスクを使ってスレッドを作成します.
1114 ワード
springの非同期タスクを使ってスレッドを作成します.
注@Configrationを使って文脈を設定します.以前のapplitionContect.xmlでbeanをロードしません.
a b b a a a a
注@Configrationを使って文脈を設定します.以前のapplitionContect.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 a a a