带返回值的java多线程

package MultiThread;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyCallable implements Callable{ 
    int pauseTime;
	String name;

    MyCallable(int x, String n) { 
            this.name = n;
            this.pauseTime = x;
    } 

    @Override 
    public Object call() throws Exception { 
    	int i = 0;
		while(i++<10) {
			System.out.println(name + ":" + new Date(System.currentTimeMillis()));
			try {
				Thread.sleep(pauseTime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
        return name + " returned"; 
    } 
}

public class CallableTest {

	/**
	 * @param args
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// TODO Auto-generated method stub
		ExecutorService pool = Executors.newFixedThreadPool(2);
		
		Callable c1 = new MyCallable(1000, "Fast Guy"); 
        Callable c2 = new MyCallable(3000, "Slow Guy"); 
        
        Future<String> f1 = pool.submit(c1); 
        Future<String> f2 = pool.submit(c2); 
        
        System.out.println("task submit");
        
        System.out.println(">>>"+f1.get()); 
        System.out.println(">>>"+f2.get()); 
        
        System.out.println("end");
        
        pool.shutdown();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值