我正在创建一个多线程网络服务器。当我运行客户端时,我收到 NullPointException。为什么会发生这种情况以及可以采取什么措施来解决它?
Concerning the suggestions that I should read the mentioned tutorial. I have tried to solve the problem with the help of it. I created a constructor, but then I didn't know how to call the class:
theExecutor.execute(new Broadcaster (connection);
I also created a setter:
public void setQuestions(String[] questions) { this.questions[1] = questions[1];}
That didn't help either. The String is initialized at the same place as
questions[0]
. I can print outquestions[1]
in the console. It get's its value from the ArrayList, but I do not know how to pass that value to the HandleValidation class. That seems to be the problem. If I have missed something in the tutorial that is an obvious solution, please tell me!
在这里您可以阅读异常消息和堆栈跟踪:
Exception in thread "pool-1-thread-2" java.lang.NullPointerException
at HandlleValidation.run(QuizServer.java:121)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745
这里我正在初始化处理线程的执行器:
public class QuizServer {
public static void main(String[] args) throws IOException {
ExecutorService theExecutor = Executors.newFixedThreadPool(10000);
ServerSocket quizSocket = new ServerSocket(serverPort);
try {
while (true) { //Skriver ut While True
Socket connection = quizSocket.accept();
theExecutor.execute(new Broadcaster(connection));
theExecutor.execute(new HandlleValidation(connection));
}
字符串问题[1]的起源位于 Broadcaster 类中:
我正在使用 get 和 set 方法来使其他内部类能够使用
String questions[];
static class Broadcaster extends Thread {
String quizFile = "src/qa.txt";
private Socket connection;
private PrintStream write;
private String answer;
private String questions[];
int points = 0;
public String[] getQuestions() {
return questions;
}
Here are the Strings
questions[0]
andquestions[1]
created:
while (true) {
for (String string : questionsList) {
String[] questions = string.split("/");
write.println(questions[0]); //Printing out in client.
try {
Thread.sleep(4000); //"Sleeping" between the lines.
} catch (InterruptedException e) {
e.printStackTrace();
}
NullPointerException 发生在 HandleValidation 类中:
class HandlleValidation extends Thread {
问题是由这一行引起的:
if (answer.equals(questions[1])) {
points++;
writer.println("RÄTT SVAR! Du har " + points + " poäng");
二传手:
public void setQuestions(String[] questions) {
this.questions = questions;
I have tried to include as little of the code as possible to describe the problem. I may be able to give more information if requested!
最佳答案
我在 for (String string: questionsList) {
的上下文中看到该变量,并且在另一个时刻您在 if (answer.equals (questions [1])) {
:即在其他上下文中,在其他范围内。
我的建议是将该变量声明在 for
范围之外。
关于java - 是什么导致线程 "pool-1-thread-2"中出现异常(NullPointerException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43400548/