java线程,线程返回值

发布于 2024-10-25 21:25:59 字数 4510 浏览 1 评论 0原文

我是线程新手,这是我在 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 方法有一个为 vale 设置的线程getReult 在 jvm 调用 getResult 方法并打印 null 值之前需要一些时间,我希望首先 main 方法完成,然后调用 getResult 方法。或我从 run 方法返回值的任何方式

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. 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. or any way from which i return value from my run method

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

┈┾☆殇 2024-11-01 21:25:59

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

Your class RS232Example has a member field String threadResult which is returend on 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.

狼性发作 2024-11-01 21:25:59

您能详细说明一下您的问题吗?它并没有清楚地表明您遇到了什么问题。我认为,您没有正确设置该值。由于 getResult() 返回一个“null”对象。让我们知道您正在执行哪些处理来获取该值。

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. Let us know what processing you are doing to get the value.

Smile简单爱 2024-11-01 21:25:59

看起来您正在访问结果后设置它。即您不必等待结果被设置。

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

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

It looks like you are setting the result after you are accessing it. i.e. you don't wait for the result to be set.

I suggest you consider using a Callable<String> and an 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文