线程中的Java变量

时间:2016-09-09 20:00:48

标签: java multithreading

我已经在这里阅读了一些问题/答案,但我仍然对java线程和变量如何工作感到困惑。

我的软件为连接一些升级版本的REST API的某些事件打开了一个连续的URL侦听器,但我会离题。所以这是一个汇总的代码块。

public static void main(String[] args) {
    //open the long-running URL
    conn = (HttpURLConnection) url.openConnection();

    // Start to receive the event notification.
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));


    // Read a complete event. Process the event.
    String str = sb.toString();
    sb.delete(0, sb.length());

    // Parse the alarm and send to the sub-processor if necessary 
    log4j.debug("Start Event Parsing");
    ParseAlarm.parseXML(str);
    Thread newAlarm = new Thread(new CreateAlarm());
    newAlarm.start();
}

请注意,这就是修复一个错误,如果在解析完成之前收到第二个事件,其中一个就会丢失。

  1. 如果我将ParseAlarm.parseXML(str)移动到newAlarm线程(触发其他线程以维持顺序),那么所有子线程都可以访问公共变量(有些是数组,有些是int / strings )在parseXML中声明或我是否需要将变量传递给每个子线程?

  2. 如果parseXML中声明的公共变量可用于newAlarm的所有子线程,那么如果主脚本再次触发newAlarm会发生什么?公共parseXML变量是否与其他线程中的变量冲突?

  3. ParseAlarm就是这样。饶恕代码中不敬的部分。请注意,它还没有设置线程。

    public class ParseAlarm {
    
      public static int intAlarmID;
      public static String strAlarmDesc;
      public static Map<String, String> mXML = new HashMap<String, String>();
    
    public static void ParseXML(String strXML) throws Exception {
      for (int i = 0; i < arElementList.length; i++) {
       //parse the elements in the XML
      }
     // Create the alarm ID as an integer for the alarm acknowledgement and the alarm description for the filter 
        intAlarmID = Integer.parseInt(mXML.get("id"));
        strAlarmDesc = mXML.get("alarmDesc");
    }
    
    }
    

    我已经能够通过引用它们来访问从其他线程声明为public的变量:     public static Map mAlarm = ParseAlarm.mXML;     private int intID = ParseAlarm.intAlarmID;

    这不应该发生,还是我完全做错了?

0 个答案:

没有答案