I am new to threads and I have a class which executes a thread. That thread class has a variable “errors” which will be set during its end. After that i need to access that variable in the main thread. How can it be possible. Please help me on this. Below is my snippet.
public class ThreadSample {
public static void main(String args[]) {
new ThreadSample().threadExample();
// Need to access errors variable here
}
public void threadExample() {
MyThread m1 = new MyThread();
}
}
class MyThread extends Thread {
String errors ;
MyThread() {
start();
}
public void run() {
// my code goes here
}
}
Thanks.
Edit:
If you are joining with the thread (i.e. waiting for it to finish) then you can just access errors afterwards and the main thread’s memory will be synchronized by the Java thread API:
If you want to access the errors variable while the thread is still running, you have a couple of options. You can mark the variable
volatilewhich means that changes are seen by all threads:Other ways to pass objects around is to use
AtomicReferenceto set and get the object in question or to use thesynchronizedkeyword to make sure that the background thread’s value of errors gets synchronized with the main thread. @claesv’s answer has a good example there.