顧名思義:同步任務是指事情需要一件一件的做,做完當前的任務,才能開始做下一任務;異步任務是指做當前任務的同時,后臺還可以在執行其他任務,可理解為可同時執行多任務,不必一件一件接著去做,下面開始上例子了
1.同步任務
/*?* @(#)SyncTaskExecutorTest.java?? ?2011-4-27?*?* Copyright (c) 2011. All Rights Reserved.?*?*/package org.jsoft.opensource.demos.spring.task;import org.junit.Test;import org.springframework.core.task.SyncTaskExecutor;/**?* Spring同步任務處理?*?* @author <a href="mailto:hongyuan.czq@taobao.com">Gerald Chen</a>?* @version $Id: SyncTaskExecutorTest.java,v 1.1 2011/05/30 08:58:07 gerald.chen Exp $?*/public class SyncTaskExecutorTest {?? ?@Test?? ?public void test() throws InterruptedException {?? ??? ?SyncTaskExecutor executor = new SyncTaskExecutor();?? ??? ?executor.execute(new OutThread());?? ??? ?System.out.println("Hello, World!");?? ??? ?Thread.sleep(10000 * 1000L);?? ?}?? ??? ?static class OutThread implements Runnable {?? ??? ?public void run() {?? ??? ??? ?for (int i = 0; i < 1000; i++) {?? ??? ??? ??? ?System.out.println(i + " start ...");?? ??? ??? ??? ?try {?? ??? ??? ??? ??? ?Thread.sleep(2 * 1000L);?? ??? ??? ??? ?} catch (InterruptedException e) {?? ??? ??? ??? ??? ?// TODO Auto-generated catch block?? ??? ??? ??? ??? ?e.printStackTrace();?? ??? ??? ??? ?}?? ??? ??? ?}?? ??? ?}?? ??? ??? ?}}

必須在線程任務執行完畢之后,"Hello,World!"才會被打印出來
2.異步任務
?/*
?* @(#)AsyncTaskExecutorTest.java?? ?2011-4-27
?*
?* Copyright (c) 2011. All Rights Reserved.
?*
?*/
package org.jsoft.opensource.demos.spring.task;
import org.junit.Test;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
/**
?* Spring異步任務處理
?*
?* @author <a href="mailto:hongyuan.czq@taobao.com">Gerald Chen</a>
?* @version $Id: AsyncTaskExecutorTest.java,v 1.1 2011/05/30 08:58:07 gerald.chen Exp $
?*/
public class AsyncTaskExecutorTest {
?? ?@Test
?? ?public void test() throws InterruptedException {
?? ??? ?AsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("sys.out");
?? ??? ?executor.execute(new OutThread(), 50000L);
?? ??? ?System.out.println("Hello, World!");
?? ??? ?Thread.sleep(10000 * 1000L);
?? ?}
?? ?
?? ?static class OutThread implements Runnable {
?? ??? ?public void run() {
?? ??? ??? ?for (int i = 0; i < 100; i++) {
?? ??? ??? ??? ?System.out.println(i + " start ...");
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?Thread.sleep(2 * 1000L);
?? ??? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?}
?? ??? ?
?? ?}
}

"Hello,World!"被正常打印出來,線程任務在后臺靜靜地執行.
?
關鍵詞:JAVA?? Spring?? 任務?? 同步?? 異步??? 軟件工程師?? 程序員?? 編程
?
posted on 2011-06-08 20:53
jadmin 閱讀(763)
評論(0) 編輯 收藏