简体   繁体   English

java线程,从线程返回值

[英]java thread ,return value from thread

i am new to threading ,this is my code in main method i have a thread that process some value then i set the value to getResult() method. 我是线程技术的新手,这是我在主要方法中的代码,我有一个线程处理一些值,然后将值设置为getResult()方法。 now i am try to get that value but i am getting null 现在我试图获得该值,但我却没有了

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

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

result is 结果是

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())

actually the object calls first main method and then getResult but as main method has a thread that set vale for getReult it take some time before that jvm call getResult method and prints null value i want that first the main method completes then getResult method is called. 实际上,该对象首先调用了main方法,然后调用getResult,但是由于main方法具有为getReult设置vale的线程,因此jvm调用getResult方法并输出null值需要一些时间,我希望首先完成main方法然后调用getResult方法。 or any way from which i return value from my run method 或我从运行方法返回值的任何方式

Your class RS232Example has a member field String threadResult which is returend on getResult . 您的RS232Example类具有一个成员字段String threadResult ,该成员字段在getResult上进行折算。 However, this field is only written to in method Result (btw it is not a good idea to start method names with capital letters) but this method itself is never called in any of your code. 但是,此字段仅写入方法Result (顺便说一句,用大写字母开头的方法名称不是一个好主意),但是在任何代码中都永远不会调用此方法本身。

Can you please elaborate your question. 您能否详细说明您的问题。 It is not giving clear idea of what problem you are having. 它并没有明确说明您遇到什么问题。 I think, You have not set the value properly. 我认为,您没有正确设置该值。 As getResult() is returning a "null" object. 当getResult()返回“空”对象时。 Let us know what processing you are doing to get the value. 让我们知道您正在做什么以获取价值。

It looks like you are setting the result after you are accessing it. 好像您在访问结果后正在设置结果。 ie you don't wait for the result to be set. 也就是说,您不必等待结果被设置。

I suggest you consider using a Callable<String> and an ExecutorService. 我建议您考虑使用Callable <String>和ExecutorService。 This will allow you to wait for the result using a builtin library. 这将允许您使用内置库等待结果。

Another option is not to do this in the background at all. 另一个选择是根本不在后台执行此操作。 You don't appear to benefit from having more than one thread, it appears to just add complexity. 您似乎并没有从多于一个线程中受益,而是增加了复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM