java 多線程來平均分配任務


有一個場景,需要完成很多任務,首先想到是用多線程來完成.

主要參數:

 1:任務數量

2:線程數量

代碼分析:由於這里的任務是計算密集型的,最好的方式是線程數量和cpu核數一樣,啟動線程越多效率越低

    如果任務是IO密集型的話,線程數量可以設置大些,具體數量可以慢慢調,比如像數據酷拷貝大量數據到另一個數據庫,文件拷貝等

總結:線程不是越多越好,當設置線程數量時,可以查看cpu使用率,如果使用率比較低那可以把線程數跳高,如果cpu已經很忙了,線程數越多cpu線程切換開銷越大,造成程序效率更低下

* Version 1.0.0
* Created on 2022年3月17日
* Copyright Sms.ReYo.Cn
*/
package sms.reyo.cn.Thread;

import java.util.ArrayList;
import java.util.List;

/**    
* <B>創  建 人:</B>Administrator <BR>
* <B>創建時間:</B>2022年3月17日 上午7:06:46<BR>
* 
* @author ReYo
* @version 1.0
*/

public class NTaskPerThread {
	int task_num = 1000;
	int thread_num = 3;
	List<Task> list = new ArrayList<NTaskPerThread.Task>();
	long total = 0;//任務運行時間,用於比較不通線程數量的效率

	public static void main(String[] args) {
		NTaskPerThread perThread = new NTaskPerThread();
		perThread.test();
	}

	public NTaskPerThread() {
	}

	public void test() {

		for (int i = 0; i < task_num; i++) {
			list.add(new Task(i));
		}

		//給每個線程分配任務,應list從索引0開始,所以分配任務編號從0開始
		int num = task_num / thread_num;//這樣子可能還有余數,應該把余數也分攤
		if (task_num % thread_num != 0) {
			num++;//如果有余數(一定小於thread_num),則前面的線程分攤下,每個線程多做一個任務
		}

		for (int i = 0; i < thread_num; i++) {
			int start = i * num;
			int end = Math.min((i + 1) * num, list.size());//最后一個線程任務可能不夠
			new TaskThread(start, end).start();
		}

	}

	public class Task {
		public Task(int n) {
		}

		public void run() {
			//	          System.out.println("run task num : " + n);
			for (int i = 0; i < 10000000; i++) {
			}
		}
	}

	public class TaskThread extends Thread {
		int start;
		int end;

		public TaskThread(int start, int end) {
			this.start = start;
			this.end = end;

		}

		@Override
		public void run() {
			long s = System.currentTimeMillis();
			for (; start < end; start++) {
				list.get(start).run();
			}
			total += (System.currentTimeMillis() - s);
			System.out.println(total);//打印任務話費時間,最大的數字為總任務話費時間
		}
	}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM