Java-试图了解线程和新的Thread(this).start();

时间:2018-07-28 05:05:44

标签: java multithreading

我对Thread很陌生。我试图了解如何通过制作一个简单的程序来应用线程的用法。它似乎不起作用。该程序只要求两个输入,并在将值分配给这两个变量后立即终止。此外,如果NullPointerException变量大于threadNum,则会抛出1,能否请您解释执行此操作的正确方法? 另外,我对于使用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 !!");
}

}

1 个答案:

答案 0 :(得分:2)

HelloWorld implements Runnable表示new Thread(this)正在将Runnable传递给Thread的构造函数。您实际上并没有在当前代码中填写a。您可以像这样

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;