异步线程ExecutorService 和 Future 实战解析

 ExecutorService 是一个比复杂的类,就不赘述了,主要记录一下异步线程的执行时机,可是我一步步调试看出来的

public List<User>  findByUsername(String username) {
	   //1.准备异步线程执行器
	   ExecutorService executorService=Executors.newFixedThreadPool(1);
	   Callable<Integer> c=  new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				int sum=0;
				for(int i=1;i<10;i++)
				{
					sum+=i;
					System.out.println("sum"+sum);
				}
				System.out.println("线程执行结束");
				return 10;
			}
		};
		System.out.println("000000");//在此之前线程定义好了
       //将线程放入执行器,开始执行线程,这时候会打印出上边for循环中的内容,这是异步的,同时执行下面的代码  并返回结果的引用给Future 
	   Future<Integer> f= executorService.submit(c);
        //不再接受线程,
	   executorService.shutdown();
	 try {
		 System.out.println(11111);
		 System.out.println(22222);
         //得到线程执行返回的结构,如果异步线程没有返回就等待
		 System.out.println(f.get());
		 System.out.println(333333);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ExecutionException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    	return userRepository.findAll(UserSpec.method1(username));
        
    }

猜你喜欢

转载自blog.csdn.net/xuedengyong/article/details/82999457