2012-02-25 63 views
1

我给出了以下代码,该代码会生成一个大数组并找到最大值。搜索数组的一部分的多个线程

import java.util.Date; 
import java.util.Random; 

class FindMax { 
private static final int N = 256 * 1024 * 1024; 

public static void main(String args[]) { 
    assert(N > 0); 

    int array[] = new int [N]; 

    assert(array != null); 

    Random random = new Random(new Date().getTime()); 

    for (int i = 0; i < N; i++) { 
     array[i] = random.nextInt(); 
    } 

    Date start = new Date(); 

    int max = array[0]; 

    for (int i = 1; i < N; i++) { 
     if (array[i] > max) { 
      max = array[i]; 
     } 
    } 

    Date end = new Date(); 

    System.out.println("max: " + max); 
    System.out.println("time in msec: " + (end.getTime() - start.getTime())); 
} 
} 

我更改代码通过使多个线程,每个找到阵列的部分的最大值,然后主线程找到的最高值由线程发现最大值,使其更快。这是我到目前为止所提出的。

import java.util.Date; 
import java.util.Random; 

class FindMax extends Thread{ 
private static final int N = 256 * 1024 * 1024; 

static int array[] = new int [N]; 
static int max = array[0]; 

public void run(){ 
    for (int i = 1; i < N; i++) { 
     if (array[i] > max) { 
      max = array[i]; 
     } 
    } 

} 

public static void main(String args[]) { 
    assert(N > 0); 
    int ts = Integer.parseInt(args[0]); 


    assert(array != null); 

    Random random = new Random(new Date().getTime()); 

    for (int i = 0; i < N; i++) { 
     array[i] = random.nextInt(); 
    } 

    Date start = new Date(); 

    Thread t[] = new Thread[ts]; 
    for(int p=0; p<ts;p++){ 
     t[p] = new FindMax(); 
     t[p].start(); 
    } 





    Date end = new Date(); 

    System.out.println("max: " + max); 
    System.out.println("time in msec: " + (end.getTime() - start.getTime())); 
} 
} 

我不理解这个,所以我做错了什么?

+0

你并不是每个线程都在数组的一部分上运行,结果集('array')也没有以任何方式进行线程安全。 – 2012-02-25 01:55:42

+0

我假设的作业? – Jivings 2012-02-25 02:07:28

回答

0

你是一个良好的开端。接下来你需要做的是给FindMax类的两个成员变量来表示要搜索的范围的开始和结束。使用这两个成员变量代替for循环中的1N。然后给FindMax一个构造函数,您可以使用它来设置这两个值。然后在构建FindMax对象的循环中,为每个对象提供一个独特的搜索范围。最后,给FindMax一个成员变量来存储最大值,以便main()可以查询每个FindMax发现的最大值。

您可能想要使用Thread类的join()方法 - 它在返回之前等待Thread完成。

+0

谢谢!我完成了它,但它具有相反的预期效果。我无法适应这个评论框中的代码,所以我在这里发布了一个新问题: http://stackoverflow.com/questions/9448587/why-does-this-programs-speed-not-increase – user1231972 2012-02-25 22:21:16