[英]Java - Trying to understand Threading and new Thread(this).start();
I'm very new to Thread. 我是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? 此外,如果
threadNum
变量大于1
,它会抛出NullPointerException
请您说明执行此操作的正确方法吗? Also, I'm confused about constructing and starting a thread with new Thread(this).start();
另外,我对于使用
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
means new Thread(this)
is passing a Runnable
to the constructor of Thread
. HelloWorld implements Runnable
意味着new Thread(this)
将Runnable
传递给Thread
的构造函数。 You aren't actually filling a
in your current code. 你实际上并没有填充
a
在当前的代码。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.