即使我已经启动了线程,我也会收到空指针异常。 是否有其他方法可以设置命令或将参数传递给正在运行的线程?
public class MainClass{
public static void main(String [ ] args)
{
try{
GDBpipeWriter g = new GDBpipeWriter();
new Thread(g).start();
// Set commands
g.setcommand("run");
g.setcommand("list");
g.setcommand("list 10,20");
}catch(NullPointerException e){
}
}
}
public class GDBpipeWriter implements Runnable{
public volatile String command;
PrintWriter stdin;
public void setcommand(String com){
this.command = com;
stdin.println(command);
}
public void run(){
Process p = null;
try {
p = Runtime.getRuntime().exec("gdb a.out --interpreter=console");
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
stdin = new PrintWriter(p.getOutputStream());
stdin.flush();
stdin.println("break 4");
stdin.flush();
stdin.println("break 10");
stdin.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
最佳答案
可能是“竞争条件”,因此当您到达第一个 setcommand() 调用时未定义 stdin。
您从 main() 调用 setcommand,但尚未设置 stdin。
更新
你现在问如何做到这一点。有很多方法可以让它发挥作用。这里只有一个提议:
让 setcommand() 设置命令成员,仅此而已。在 run() 方法中放置一个 while 循环。在 while 循环中等待该命令设置,将命令发送到流并将命令重置为空。可选 sleep() 一些毫秒,然后继续循环。哈。
关于Java 线程 GDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8223246/