2011-11-22 50 views
1

即使我已經啓動線程,我也會收到空指針異常。 有沒有其他方法來設置命令或傳遞參數到正在運行的線程?Java線程GDB

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_; 
} 

回答

3

也許是「競態條件」,所以,當你到達第一個set命令()調用標準輸入沒有定義。 您可以從main()調用setcommand,但stdin沒有設置。

更新

你現在問如何做到這一點。有很多方法可以完成這項工作。這裏只有一個建議:

讓setcommand()設置命令成員,僅此而已。在run()方法中放置一個while循環。在while循環中等待該命令設置,發送命令給流並將reset命令設爲null。可選sleep()一些ms,然後繼續循環。 HTH。