你能帮我理解为什么这个项目总是显示 Id 9 吗?我的意思是输出是这样的:
FirstThread.txt
Id 9
<Some string read from the file>
...
...
SecondThread.txt
Id 9
<Some string read from the file>
我估计 Id 会有所不同。即使我停止项目并再次运行,这个 Id 也不会改变。
package parallelprogramming;
import java.lang.Thread;
import java.io.*;
public class Thrd extends Thread {
public boolean readFile(String File)/* throws FileNotFoundException */ {
try {
FileReader fr = new FileReader(File);
BufferedReader br = new BufferedReader(fr);
String s;
try {
while ((s = br.readLine()) != null) {
System.out.println(File);
System.out.println("Id " + this.getId());
System.out.println(s);
}
fr.close();
return true;
} catch (IOException IOE) {
System.out.println("IOException caught!");
return false;
}
} catch (FileNotFoundException FNFD) {
System.out.println("File not found!");
return false;
}
}
}
package parallelprogramming;
import java.awt.event.*;
import java.io.FileNotFoundException;
public class ParallelProgramming {
public static void main(String[] args) {
Thrd FirstThread = new Thrd();
Thrd SecondThread = new Thrd();
Thrd CurrentThread = null;
String File = null;
for (int i = 0; i < 1000000; i++) {
if (i % 2 == 0) {
File = "FirstThread.txt";
CurrentThread = FirstThread;
} else {
File = "SecondThread.txt";
CurrentThread = FirstThread;
}
while (!CurrentThread.isInterrupted()) {
if (CurrentThread.readFile(File)) {
break;
};
}
}
}
}
最佳答案
您的代码使用单个线程:主线程。要开始一个线程,您需要
- 扩展线程
- 覆盖其
run()
方法 - 实例化您的 Thread 子类
- 调用它的
start()
方法
或者你需要
- 创建一个Runnable
- 将它传递给线程构造函数
- 调用线程的
start()
方法
这在 the tutorial 中有清楚的解释。 .
扩展线程,在扩展类中添加一个方法(如readFile()
)并调用它,不会在另一个线程中调用该方法。
旁注:请遵守 Java 命名约定。方法和变量以小写字母开头。
关于java - 如何获取线程的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434479/