简体   繁体   中英

Java Thread instantiation with incorrect variables

I'm trying to use multithreading to break down a large block of processing data into smaller chunks.
The problem I am having is that my threads aren't running against their specified portion of the data space.

For example:

thread-2 should process range of 0 - 1000

thread-3 should process range of 1001 - 2000

When I call my new threads back to back i get:

thread-2 = 0 - 1000

thread-3 = 0 - 1000

When I add a Thread sleep(3000) in between the two thread calls i get:

thread-2 = 0 - 1000

thread-3 = 0 - 2000

I'm not sure what I'm doing wrong and would really appreciate some guidance.

Note on Snippits below, I abbreviated the above numbers actual call range in example below is

1,000,000 - 1,001,000 and 1,001,001 - 1,002,000

Snippet from main method detailing thread call:

        try {
        int start = 1000000;
        int end = 1001000;
        new Thread(new MyThread(start, end, PUBLIC_INVALID_LIST)).start();
        Thread.sleep(3000);
        start = 1001001;
        end = 1002000;
        new Thread(new MyThread(start, end, PUBLIC_INVALID_LIST)).start();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

Snippet from MyThread which extends Thread This details how I am passing params from the main method through to the run() method:

//variables to pass from constructor to run()
private int startIndex;
private int endIndex;
private ArrayList PUBLIC_INVALID_LIST;

MyThread(int startIndex, int endIndex, ArrayList PUBLIC_INVALID_LIST) {

    this.startIndex = startIndex;
    this.endIndex = endIndex;
    this.PUBLIC_INVALID_LIST = PUBLIC_INVALID_LIST;

}//end of initializer

public void run() {

still not sure what the issue was with the variable pass in, but I got an alternate pass in method to work using int[]

int sizeSet = (max /100000) + 1;//max is highest path_id value
    int[] start_range = new int[sizeSet];
    int[] end_range = new int[sizeSet];
    start_range[0] = 1;//first possible path_id
    end_range[0] = 100000;//end point of first possible range
    int rangeIndex = 1;//create counter for while loop
    while(rangeIndex < sizeSet){
        start_range[rangeIndex] = start_range[rangeIndex - 1] + 100000;
        end_range[rangeIndex] = end_range[rangeIndex - 1] + 100000;
        ++ rangeIndex;
    }//end range setting while block
    rangeIndex = 0;//reset index counter
    while(rangeIndex < sizeSet){
        new Thread(new MyThread(start_range[rangeIndex], end_range[rangeIndex], PUBLIC_INVALID_LIST)).start();
        ++ rangeIndex;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM