简体   繁体   中英

Java - Trying to understand Threading and new Thread(this).start();

I'm very new to Thread. I'm trying to understand how to apply the usage of threading by making a simple program. It doesn't seem to be working. The program just ask for two inputs and terminate right away after assigning value to those two variables. Moreover, it throws NullPointerException if the threadNum variable is more than 1 Could you please explain the proper way to do this? Also, I'm confused about constructing and starting a thread with new Thread(this).start();

package helloworld;

import java.util.Scanner;


public class HelloWorld implements Runnable {

private int threadNum;
private int taskNum;
private int loopNum;

public HelloWorld(int threadNum, int taskNum){
    this.taskNum = taskNum;
    this.threadNum = threadNum;

    int loop = taskNum / threadNum;
    this.loopNum = loop;
}

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Task Num = ");
    int taskNum = sc.nextInt();
    System.out.print("Thread Num = ");
    int threadNum = sc.nextInt();

    HelloWorld hello = new HelloWorld(threadNum, taskNum);
    hello.activate();

}


public void activate(){
    Thread[] a = new Thread[this.threadNum];
    int count = 0;

    for(Thread x : a){
        x = new Thread(this);
    }

    for(int i = 0; i < a.length - 1 ; i++){

        while(count < loopNum){
            a[i].start();
            count++;
        }
        count = 0;

        while(count < taskNum - ((threadNum - 1) * loopNum)){
            a[a.length - 1].start();
            count ++;
        }
    }
}

@Override
public void run() {

    System.out.println("Processing....");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    System.out.println("Done !!");
}

}

HelloWorld implements Runnable means new Thread(this) is passing a Runnable to the constructor of Thread . You aren't actually filling a in your current code. You can do that like

Thread[] a = new Thread[this.threadNum];
for(int i = 0; i < this.threadNum; i++){
    a[i] = new Thread(this);
}
// Now `a` is filled with threads.
int count = 0;

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