[英]Java - Trying to understand Threading and new Thread(this).start();
我是Thread的新手。 我试图了解如何通过制作一个简单的程序来应用线程的用法。 它似乎不起作用。 该程序只要求两个输入,并在将值分配给这两个变量后立即终止。 此外,如果threadNum
变量大于1
,它会抛出NullPointerException
请您说明执行此操作的正确方法吗? 另外,我对于使用new Thread(this).start();
构造和启动线程感到困惑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
意味着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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.