JAVA多線程後臺異步,和同步併發

學習地址:

https://blog.csdn.net/qq_25806863/article/details/71126867

1. 同步併發獲取結果:

    // 開通3個同步線程 空閒下進行
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    List<Callable<Object>> searchTasks = new ArrayList<Callable<Object>>(); 
    // 根據查詢shop 線程
     Callable<Object> shopCall =  new ShopCall();
    searchTasks.add(shopCall);
    searchTasks.add(shopCall);
    searchTasks.add(shopCall);
    //invokeAll 第一個參數是任務列表;第二個參數是過期時間;第三個是過期時間單位  
		try {
			logger.debug(">>> Starting runing thread");
			List<Future<Object>> futures = executorService.invokeAll(searchTasks,20, TimeUnit.SECONDS);

			jsonObject.put("shop", futures.get(0).get());

			
			executorService.shutdown();
			
		} catch (Exception e) {
			logger.error("Thread Error:{}",e);
			throw new RuntimeException("異步獲取數據失敗: "+e.getMessage());
		}

    /**
	 *  獲取用戶信息
	 * 
	 *
	 * 
	 */
	private class ShopCall implements Callable<Object>{

		public ShopCall() {

		}
		@Override
		public Object call() throws Exception {
			logger.debug(">>> Geting shop information:{}",slug);
			return null ;
		}
	}

異步後臺線程:不關心結果

// 後臺異步執行 execute
public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		Runnable myRunnable = new Runnable() {
    	    @Override
    	    public void run() {
    	        try {
    	            Thread.sleep(2000);
    	            System.out.println(Thread.currentThread().getName() + " run");
    	        } catch (InterruptedException e) {
    	            e.printStackTrace();
    	        }

    	    }
    	};
	     executorService.execute(myRunnable);
	     executorService.execute(myRunnable);
	     executorService.execute(myRunnable);
	     executorService.shutdown();
	    System.out.println("返回數據");
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章