需求:并行执行求得耗时长;

描述:时间长度不应用是各个线程里的耗时长相加,而应该是减去(n-1)次相交的时长 ,n为相交次数

知识点:多线程,TreeSet

注意:treeSet(其排序与是否相等都依赖对象的compareTo方法,而与equals无关

代码实现:

View Code
 1 public static long process(List<NThreadTimeObj> ts)
 2     {
 3         long countTime = 0;
 4         //过滤重复并排序
 5         Set< NThreadTimeObj> set = new TreeSet<NThreadTimeObj>(ts);
 6         
 7         Iterator<NThreadTimeObj> it = set.iterator();
 8         
 9         NThreadTimeObj temp = it.next();
10         
11         while(it.hasNext())
12         {
13             NThreadTimeObj t = it.next();
14             if(temp.getEnd() >=t.getBegin())
15             {
16                 if(temp.getEnd()<=t.getEnd())
17                 {
18                     temp.setEnd(t.getEnd());
19                 }
20             }
21             else
22             {
23                 countTime +=temp.TimeLong();
24                 temp = t;
25             }
26         }
27         countTime += temp.TimeLong();
28         return countTime;
29     }

Object:

 1 public class NThreadTimeObj implements Comparable<NThreadTimeObj> {
 2     
 3     private long begin;
 4     private long end ;
 5     
 6     
 7     public NThreadTimeObj(long begin, long end)
 8     {
 9         this.begin = begin;
10         this.end = end;
11     }
12 
13     public long TimeLong()
14     {
15         return end-begin;
16     }
17     
18     
19     @Override
20     public int compareTo(NThreadTimeObj other) {
21         if(this.begin == other.begin)
22         {
23             return (int)(this.end - other.end);
24         }
25         return (int)(this.begin-other.begin);
26     }
27 
28     @Override
29     public String toString() {
30         return begin +"---"+ end;
31     }
32     
33     public long getBegin() {
34         return begin;
35     }
36     public void setBegin(long begin) {
37         this.begin = begin;
38     }
39     public long getEnd() {
40         return end;
41     }
42     public void setEnd(long end) {
43         this.end = end;
44     }
45 }