我正在尝试使用 threadname1、threadname2、..threadnamen 等变量创建多个线程。我没有将其作为硬编码值,而是尝试使用 for 循环来处理 n 个数字,并在“threadname”字符串的末尾使用它。它会抛出一些错误。我该如何解决这个问题?
public class RunnableExample{
public static void main(String[] args){
String Name = "";
String Ip = "";
for (int i=1; i<=2; i++){
if(i == 1){
Name = "irony";
Ip = "82.209.27.24";
}
else{
Name = "jocky";
Ip = "98.12.098.56";
}
String runname = "threadname" + i;
RunnableThread runname = new RunnableThread(Name,Ip);
new Thread(runname).start();
}
//RunnableThread threadname1 = new RunnableThread("irony","82.209.27.24");
//RunnableThread thread4 = new RunnableThread("jocky","98.12.098.56");
//new Thread(threadname1).start();
//new Thread(threadname2).start();
try{
}
catch (InterruptedException e) {
}
}
输出:
bash-3.00# javac RunnableExample.java
RunnableExample.java:43: runname is already defined in main(java.lang.String[])
RunnableThread runname = new RunnableThread(Name,Ip);
如何解决这个问题?也许看起来需要一些类型转换。我不确定。
这是你的问题:
String runname = "threadname" + i;
RunnableThread runname = new RunnableThread(Name,Ip);
您试图声明两个同名的变量。你不能那样做。更改其中一个变量的名称。 Java 中变量的名称在编译时就固定了。你不能说“用 this 变量的执行时值的名称声明一个变量”,这就是我认为你想要做的。
如果您想要访问多个值的方法,请使用集合或数组。例如,您可能需要一个
List<RunnableThread>
- 在循环的每次迭代中将值添加到列表中。
我还强烈建议您在开始尝试线程之前,确保了解 Java 的基础知识(例如变量和集合)。线程很复杂并且很难推理——如果你在核心语言上遇到困难,那就更难了。
String Name = "threadname" + i;
RunnableThread runname = new RunnableThread(Name,Ip);
String threadName = "threadname" + i;
RunnableThread runname = new RunnableThread(threadName, ip);
如果您使用 Java,最好的做法是使用 Java 命名约定。例如,所有变量都以小写字母开头。
您可能想这样做:
import java.util.HashMap;
import java.util.Map;
public class RunnableExample {
public static void main(String[] args) {
Map<String, RunnableThread> threadMap = new HashMap<String, RunnableThread>();
String name = "";
String ip = "";
for (int i = 1; i <= 2; i++) {
if (i == 1) {
name = "irony";
ip = "82.209.27.24";
} else {
name = "jocky";
ip = "98.12.098.56";
}
String threadName = "threadname" + i;
RunnableThread thread = new RunnableThread(name, ip);
new Thread(thread).start();
threadMap.put(threadName, thread);
}
threadMap.get("threadname1").getIp();
}
}
Thread ironyThread = new RunnableThread("irony", "82.209.27.24");
Thread jockyThread = new RunnableThread("jocky", "98.12.098.56");
ironyThread.start();
jockyThread.start();
类似的东西会做你正在尝试的事情。我知道你说过你希望它处理 N 个线程。我的解决方案仍然比您遵循的模式更清晰;在每次迭代中为不同的 threadName 值添加 if 检查。