简体   繁体   中英

Java: Why method is not called when inside the thread?

i have a method:

public String getPresentValue(ObjectIdentifier oid) throws Exception {
    ReadPropertyRequest rpr = new ReadPropertyRequest(oid, PropertyIdentifier.presentValue);
    ReadPropertyAck rpa = (ReadPropertyAck) localDevice.send(isa, null, 1476, Segmentation.segmentedBoth, rpr);

    return rpa.getValue().toString();
}

That works perfectly when i call it outside of the thread, but when i try to call it inside of the thread, nothing happens.

Why this happens?

Update:

public void active(Supervisory supervisory) {

       //.. my code above is just simple maths

        System.out.println("presentValue in the thread" + getPresentValue(oi));


        ScanAO scanAO = new ScanAO();

        Thread threadAO = new Thread(scanAO);
        threadAO.start();

    } catch (IOException ioe) {
        ioe.printStackTrace();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}


    class ScanAO extends Thread {

        public void run() {
            try {

                for (ObjectIdentifier oi : oisAO) {
                    System.out.println("presentValue in the thread" + getPresentValue(oi));
                }

            } catch (Exception e) {
            }

        }
    }

Best regards, Valter Henrique.

Could the problem be with "oisAO"? If your getPresentValue() works outside the thread it should probably work inside the new thread. It might be what you are passing into the function.

Just to be clear: when you call the code with .start() (with multi-threading) you get an exception and when you change threadAO.start() to threadAO.run() (without multi-threading) it works properly?

Probably oisAO is not synchronized between threads: the original thread modifies the state of oisAO (closes the socket) before the new thread created by .start() can do its job. To identify if this is the problem, you could try adding a threadAO.join() (pause the current thread until the new thread is done) right after threadAO.start() .

If this is the problem, you should give more thought to find a correct solution since just pausing the original thread might give you some performance issues. If you pause the thread it's not really multi-threaded, but basically just code running on two threads sequentially.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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