简体   繁体   中英

Read a thread Field from an other class

I'm running a computation expensive code in background with the use of thread. This code return progress as he run. And in the main thread i want to read this value so i can show the user the progress

Here is my setup : A process class :

Public class ProcessThread implements Runnable {
    public int progress;

    ProcessThread{
    }

    public void run(){
        // Update progress as the processing goes
    }
}

And a main class:

Public class MainClass {

    Private ProcessThread myProcessThread;

    MainClass{
       myProcessThread = new ProcessThread();
       (new Thread(myProcessThread)).start();
    }

    Public void readProcess(){
        // Called from anywere in the main thread.
        System.out.print("Progress = " + myProcessThread.progress);
    }
}

I wanted to know the best way to lock variables (using wait(), notify(), ...) so it's thread safe to read and write them.

Thanks for any advice.

Best

You do not need to synchronize reading of the process variable. One thing you could do is to make it volatile to ensure that the main thread sees the latest state of the variable.

On volatile :

  • (In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it's generally not a useful threading construct.)

  • (In Java 5 or later) Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.[9]

使用AsyncTask

onProgressUpdate(Progress...)

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