![](/img/trans.png)
[英]Java multi-thread switching context vs submit new task and solution for monitoring a queue
[英]Asynchronous vs new Thread - Need help for a solution (Java)
我有一種方法,當前需要將結果返回給客戶端的速度不比當前速度慢。 因此,它必須調用一個方法並忘記它,它應該繼續處理而不要等待該方法返回任何結果。 我一直在玩ejb @Asynchronous批注,也使用新的線程。 我發現以下內容:
方式1:使用@Asynchronous-調用此方法時,調用方似乎正在等待。 此方法返回void,所以我認為調用方會調用它並繼續前進,但事實並非如此。 來電顯示:
public static void main(String[] args) {
System.out.println("Caller Starting");
Processor p = new Processor();
p.doSomeStuff();
System.out.println("Caller Ended");
}
public class Processor{
@Asynchronous
public void doSomeStuff() {
System.out.println("Async start");
for(int i = 0; i < 50; i++) {
System.out.println("Async: " +i);
}
System.out.println("Async ended");
}
}
方式2:使用新線程 -以這種方式執行操作時,它會執行我想要的操作。
public static void main(String[] args) {
System.out.println("Caller Starting");
Processor p = new Processor();
p.doSomeStuff();
System.out.println("Caller Ended");
}
@Stateless
公共類處理器擴展線程{
public void doSomeStuff() {
start();
}
@Override
public void run() {
// Loop for ten iterations.
for(int i=0; i<10; i++) {
System.out.println(i + " looping ...");
// Sleep for a while
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// Interrupted exception will occur if
// the Worker object's interrupt() method
// is called. interrupt() is inherited
// from the Thread class.
break;
}
}
}
我使用@Asynchronous注釋不正確嗎?
有什么好的解決方案來滿足這一要求? 有沒有更好,更簡單的方法來滿足要求?
使用@Asynchronous注釋與創建新線程時具有相同的作用,但麻煩較少。 在您的情況下,您使用的注釋不正確。 異步方法必須在無狀態Bean中,才能在不等待調用方方法等待的情況下運行。 所以大概應該可行,
@Stateless
public class Processor{
@Asynchronous
public void doSomeStuff() {
System.out.println("Async start");
for(int i = 0; i < 50; i++) {
System.out.println("Async: " +i);
}
System.out.println("Async ended");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.