Create a runnable and use the settings and getters that you define in the specified runnable.
public class MyRunnable implements Runnable{ private volatile String myString; public String setString(String value){this.myString = value;} public String getString(){ return myString; } public void run(){} }
The volatile keyword is used here. The volatile keyword ensures that this line changes in one thread so that all threads see the change. If instead I guarantee that the only access to the String object is through a synchronized context, then the volatile keyword is not required.
To demonstrate our point of view, the code above and the code below are thread safe, but different from each other, since none of the 2 threads can enter setString and getString at the same time in the example below.
public class MyRunnable implements Runnable{ private String myString; public synchronized String setString(String value){this.myString = value;} public synchronized String getString(){ return myString; } public void run(){} }
The thread really just runs runnable. You can use it like this:
MyRunnable runnable = new MyRunnable(); Thread myThread = new Thread(runnable); myThread.start(); String myString = runnable.getString();
Using atomic values ββfor primitives is fine, but if you ever want to share a more complex object, you will need to read about thread and synchronization.
For instance:
public class Stats{ int iterations; long runtime; public Stats(){ iterations = 0; runtime=0; } public synchronized void setIterations(int value){this.iterations = value;} public synchronized void setRuntime(long milliseconds){ this.runtime = milliseconds; } public synchronized int getIterations(){ return iterations; } public synchronized long getRuntime(){return runtime;} } public class StatRunnable implements Runnable{ Stats stats; boolean active; public StatRunnable(){ this.active=true; } public Stats getStats(){ return stats; } long calculateRuntime(){return 0L;} public void run(){ while(active){
This code shows an example of synchronization with non-primitive objects using the synchronized . Using the synchronized keyword in a method definition blocks the class, using itself as a synchronization object.
Finally, the synchronized keyword is used not only in method definitions. You can use it to synchronize instances in methods, as was done in the run method, in StatRunnable .