java 多线程来平均分配任务

有一个场景,需要完成很多任务,首先想到是用多线程来完成.

主要参数:

 1:任务数量

2:线程数量

代码分析:由于这里的任务是计算密集型的,最好的方式是线程数量和cpu核数一样,启动线程越多效率越低

    如果任务是IO密集型的话,线程数量可以设置大些,具体数量可以慢慢调,比如像数据酷拷贝大量数据到另一个数据库,文件拷贝等

总结:线程不是越多越好,当设置线程数量时,可以查看cpu使用率,如果使用率比较低那可以把线程数跳高,如果cpu已经很忙了,线程数越多cpu线程切换开销越大,造成程序效率更低下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
* Version 1.0.0
* Created on 2022317
* 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);//打印任务话费时间,最大的数字为总任务话费时间
        }
    }
 
}

 

posted @   锐洋智能  阅读(846)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· Windows 提权-UAC 绕过
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-03-17 java.io.IOException: Attempted read from closed stream解决
2014-03-17 Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.
点击右上角即可分享
微信分享提示