1. 程式人生 > >java.util.concurrent多執行緒簡單demo及計算多執行緒程式執行時間

java.util.concurrent多執行緒簡單demo及計算多執行緒程式執行時間

 
	public void doMain(String dir) {
		// 獲取開始時間
		long startTime = System.currentTimeMillis();
		try {
			 File file = new File(dir);
			File[] files = file.listFiles();
			ExecutorService executorService = Executors.newFixedThreadPool(30);
			 
			int size =1000;
			for (int i = 0; i < size; i++) {
				final int index = i;
				final File fileNow = files[index];


				Runnable run = new Runnable() {
					public void run() {
						System.out.println((index + 1) + "/" + length + "....");
						// 目錄
						if (fileNow.isDirectory()) {
							 System.out.println(files[i].getName() + ":目錄");
							getFilesFromDirThread(fileNow.getAbsolutePath());
						}
						else {// 檔案
							if (fileNow.getName().endsWith(".html")) {
								System.out.println(fileNow.getName() + ":檔案");
								doMyJob(fileNow.getAbsolutePath());
							}
						}  
					}
				};
				executorService.execute(run);
			}// end for 

			executorService.shutdown();


			try {
				boolean loop = true;
				do { // 等待所有任務完成
					loop = !executorService.awaitTermination(2,
							TimeUnit.SECONDS);
				} while (loop);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}


			// 獲取結束時間
			long endTime = System.currentTimeMillis(); 

			// 輸出程式執行時間
			System.out.println("程式執行時間:" + (endTime - startTime) + "ms"); 

		} catch (Exception e) {
		}


	}