posts - 495,  comments - 11,  trackbacks - 0

顾名思义:同步任务是指事情需要一件一件的做,做完当前的任务,才能开始做下一任务;异步任务是指做当前任务的同时,后台还可以在执行其他任务,可理解为可同时执行多任务,不必一件一件接着去做,下面开始上例子了

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 阅读(757) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: