zoukankan      html  css  js  c++  java
  • 带返回值的线程

    public class returnThread {
    	public static void main(String[] args) throws InterruptedException, ExecutionException {
    		ExecutorService service = Executors.newCachedThreadPool();          // 创建线程池
    		ArrayList<Future<String>> list = new ArrayList<Future<String>>();   // Future<String> 用来接收单个线程的返回值
    		int i =1;
    		while(i<=10){
    			list.add(service.submit(new calltest(i)));   //通过 submit 实现了Callable的类,获取返回值
    			i++;
    		}
    		
    		for(Future<String> li : list){
    			System.out.println(li.get());  //调用get()方法获取返回的内容,这里get()方法会阻塞,就是说等所有线程执行完毕,get()方法才会运行。
    		}
    		
    	}
    	
    	
    }
    
    class calltest implements Callable<String>{
    	private int i;
    	
    	public calltest(int i){
    		this.i = i;
    	}
    
    	@Override
    	public String call() throws Exception {                    //该方法为必须实现,调用线程,触发该方法。
    		System.out.println("calltest.call()"+i);
    		Thread.sleep(5000);
    		return "线程"+i;
    	}
    	
    }
    
    
  • 相关阅读:
    Shell 数组
    Shell 中的中括号用法总结
    设置Linux可以查看历史命令(history)的执行时间
    jasypt 对 配置文件密码进行加密处理
    今日进度
    今日进度
    今日进度
    今日进度
    今日进度
    每周总结
  • 原文地址:https://www.cnblogs.com/heiniao/p/5805390.html
Copyright © 2011-2022 走看看