【问题标题】:java thread ,return value from threadjava线程,从线程返回值
【发布时间】:2011-03-22 05:42:28
【问题描述】:

我是线程新手,这是我在 main 方法中的代码,我有一个线程处理一些值,然后我将值设置为 getResult() 方法。现在我正在尝试获取该值,但我得到了 null

 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,但是由于 main 方法有一个线程为 getReult 设置值,所以在 jvm 调用 getResult 方法并打印空值之前需要一些时间,我希望首先 main 方法完成,然后 getResult 方法叫做。或者我从我的运行方法返回值的任何方式

【问题讨论】:

  • 能否请您出示相关代码

标签: java multithreading


【解决方案1】:

您的班级RS232Example 有一个成员字段String threadResult,它在getResult 上返回。但是,此字段仅写入方法 Result 中(顺便说一句,以大写字母开头的方法名称不是一个好主意),但此方法本身永远不会在您的任何代码中调用。

【讨论】:

  • 嗨,感谢您的回复和建议,但我将结果方法称为 weightRs232.Result(val);
【解决方案2】:

您能否详细说明您的问题。它没有清楚地说明您遇到了什么问题。我认为,您没有正确设置值。由于 getResult() 返回一个“null”对象。让我们知道您正在做什么处理以获得价值。

【讨论】:

  • 实际上对象调用了第一个main方法然后getResult但是
【解决方案3】:

看起来您是在访问结果后设置结果。即,您无需等待设置结果。

我建议您考虑使用 Callable 和 ExecutorService。这将允许您使用内置库等待结果。

另一种选择是根本不在后台执行此操作。您似乎没有从拥有多个线程中受益,它似乎只是增加了复杂性。

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 2013-11-06
    • 2012-02-27
    • 2021-10-24
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多