SharedValue.java
package egtry.thread;
public class SharedValue extends Thread {
private static long sharedValue; //regular shared variable
public static void main(String[] args) throws Exception {
SharedValue thread1=new SharedValue();
thread1.start();
SharedValue thread2=new SharedValue();
thread2.start();
SharedValue thread3=new SharedValue();
thread3.start();
}
@Override
public void run() {
Thread t=Thread.currentThread();
long id=t.getId();
for(long i=0; i<100; i++) {
sharedValue=id; //update the shared value by this thread
Sleep(10); //hold the execution for 10 milliseconds
if (id !=sharedValue) {
System.out.println(id+": ERROR: val was modified by other thread");
break;
}
}
System.out.println(id+": done");
}
public static void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}