Home Android Thread Safety; Data Injection into a thread
Reply: 0

Android Thread Safety; Data Injection into a thread

user2011
1#
user2011 Published in October 20, 2017, 7:56 pm

I have created an example:

import static java.lang.Thread.sleep;

public class Example implements Runnable, IExternal {

    Object o = null;
    // Construstor with parameters for the thread
    Example(Object o){ 
        this.flag = (Boolean)o; 
        Controller.IExtOfExample = (IExternal) this;
    }

    volatile Boolean flag = true;
    Object p1, p2 = null;
    public volatile String result= "";

    @Override
    public void run() {
        while (flag){
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // some code
            result = p1.toString() + p2.toString();
        }

    }

    @Override
    public void Reset() {
        flag = false;
    }

    @Override
    public Boolean MethodB(Object o1, Object o2) {
        p1 = o1; p2 = o2;
        return true;
    }
}

interface IExternal{
    void Reset();
    Boolean MethodB(Object o1, Object o2);
}

class Controller {
    public static IExternal IExtOfExample = null;
}

//from somewhere..

class MainApp{

    void Method(){
        Example ex = new Example(true);
        try {
            Thread example = new Thread(ex);
            example.start ();
        } catch (Exception e) {
            e.printStackTrace ( );
        }
        // What is Thread safe?
        // This
        Controller.IExtOfExample.MethodB("Parameter 1", "Parameter 2");
        String ret = ex.result;
        Controller.IExtOfExample.Reset();
        // or that
        ex.MethodB("Parameter 1", "Parameter 2");
        ret = ex.result;
        ex.Reset();
    }
}

Is the Thread compartment term available in Android Java?

When I start the Thread, which part of code will be placed into the Thread compartment : only method RUN or the whole object of the treadable class?

How to inject data inside the tread safely : using interface or using the pointer to the class' object?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.458359 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO