2011-03-22 5 views
0

나는 스레딩에 새로운 오전, 이것은 주된 방법으로 내 코드입니다. getResult() 메소드에 값을 설정 한 후 일부 값을 처리하는 스레드가 있습니다. 지금 나는 그 값을 얻으려고하지만 난 널자바 스레드, 스레드에서 값을 반환

RS232Example rs232= new RS232Example(); 
rs232.main() 

System.out.println("value after RS232::"+rs232.getResult()) 

결과를 얻고있다

value after RS232::null 
call 
call 
call 
call 
call 
call 
call 
call 
call 
call 
call 
0 
:: 0 
::::?? 0 
call 




public class RS232Example implements rs232Weight{ 

    private String threadResult; 

    public void Result(String result) { 
     threadResult = result; 

    } 
    public String getResult() { 
      return threadResult; 
    } 

     public synchronized void connect(String portName) throws Exception { 

      CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); 
      SerialPort serialPort=null; 
      if (!portIdentifier.isCurrentlyOwned()) { 
      serialPort = (SerialPort) portIdentifier.open("RS232Example", 2000); 

       // setup connection parameters 
       // set the parameter for machine 

       serialPort.setSerialPortParams(
         9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN); 
       // setup serial port writer 
       CommPortSender.setWriterStream(serialPort.getOutputStream()); 

      // setup serial port reader 
      CommPortReceiver obj = new CommPortReceiver(serialPort.getInputStream(),serialPort); 

      obj.start(); 

      } else { 
       // points who owns the port and connection timeout 
      System.out.println("Port in use!"); 
       try{ 
        portIdentifier=null; 
       } 
       catch(Exception e){ 
        System.out.println("error"+e); 
       } 
      } 
     } 

    public void main() throws Exception{ 

      // connects to the port which name (e.g. COM1) is in the first argument 
     connect("COM1"); 

      // send HELO message through serial port using protocol implementation 
      CommPortSender.send(new ProtocolImpl().getMessage("HELO")); 
     } 
    } 

==============

package com.indivar.cmcs.machine; 
import gnu.io.SerialPort; 
import java.io.IOException; 
import java.io.InputStream; 

    public class CommPortReceiver extends Thread{ 
    // public rs232Weight weightRs232; 
    // RS232Example rs232= new RS232Example(); 
     SerialPort serialPort=null; 
     String value; 
     InputStream in; 
     Protocol protocol = new ProtocolImpl(); 
     rs232Weight weightRs232= new RS232Example(); 
     private volatile boolean stopRequested=false; 
     public CommPortReceiver(InputStream in,SerialPort serialPort) { 
      this.in = in; 
      this.serialPort=serialPort; 

     } 
     int i=10; 
     public void stopRequest() { 
      stopRequested = true; 
      serialPort.close(); 
      } 
     public void run() { 
      try { 
       int b; 
      // System.out.println("f"); 
      while(!stopRequested) { 

        // if stream is not bound in.read() method returns -1 
        while((b = in.read()) != -1) { 
        String val=protocol.onReceive((byte) b); 

         if (val.equals("0")){ 
          // System.out.println("::::??"+val); 
         } 
         else{ 
          value=val; 
         //.setWeight(value); 
          System.out.println("::::??"+val); 
         stopRequest(); 
          weightRs232.Result(val); 
        break; 
         } 
         Thread.sleep(100); 
        //  
        } 

        protocol.onStreamClosed(); 

        // wait 10ms when stream is broken and check again 
       i--; 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
} 


================== 


RS232Example rs232= new RS232Example(); 
     rs232.main() 

     System.out.println("value after RS232::"+rs232.getResult()) 

사실 객체는 첫 번째 main 메소드와 getResult를 호출하지만 주 메소드는 getReult에 vale을 설정하는 스레드를 가지고 있습니다. jvm 호출 getResult 메소드와 null 값을 출력하기 전에 시간이 좀 걸립니다. 먼저 main 메소드가 완료되면 getResult 메소드가 호출됩니다. 또는 내 실행 방법에서 값을 반환하는 방법은 무엇입니까

+1

** 관련 코드 ** –

답변

0

질문을 자세히 설명해 주실 수 있습니까? 어떤 문제가 있는지 명확하게 알 수는 없습니다. 내 생각에, 너는 값을 제대로 설정하지 않았다. getResult()는 "null"객체를 반환합니다. 가치를 얻기 위해 어떤 처리를하고 있는지 알려주십시오.

+0

실제로 표시 할 수 있습니다. 개체가 첫 번째 main 메서드를 호출 한 다음 getResult를 호출하지만 – user670600

1

클래스 RS232Example에는 getResult에 returend 인 회원 필드 String threadResult이 있습니다. 그러나이 필드는 메서드 Result에만 기록됩니다 (메서드 이름을 대문자로 시작하는 것은 좋지 않습니다.)하지만이 메서드 자체는 사용자 코드에서 호출되지 않습니다.

+0

안녕하세요, 답장과 제안을 보내 주셔서 감사합니다.하지만 Result 메서드를 호출합니다. weightRs232.Result (val); – user670600

+0

하지만 스레드가 완료 될 때까지 기다리는 것을 볼 수 없습니다. – Howard

+0

예, 글을 처음 사용하는 사람입니다. 어떻게 도와 줄 수 있습니까? – user670600

0

결과에 액세스 한 후 결과를 설정하는 것처럼 보입니다. 즉, 결과가 설정되기를 기다리지 않습니다.

Callable < String> 및 ExecutorService를 사용하는 것이 좋습니다. 이렇게하면 내장 라이브러리를 사용하여 결과를 기다릴 수 있습니다.

또 다른 옵션은 백그라운드에서 전혀 수행하지 않는 것입니다. 하나 이상의 스레드가 있으면 이익을 얻는 것처럼 보이지 않습니다. 복잡성을 추가하는 것처럼 보입니다.

관련 문제