| Refresh | Home EGTry.com

shared threadlocal variable


use regular shared variable

package 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());
		}
	}
}


use threadlocal variable

package thread;

public class SharedValue_UseThreadLocal extends Thread {

	private static ThreadLocal<Long> threadLocal=new ThreadLocal<Long>(); //long value inside ThreadLocal

	public static void main(String[] args) throws Exception {
		SharedValue_UseThreadLocal thread1=new SharedValue_UseThreadLocal();
		thread1.start();
		SharedValue_UseThreadLocal thread2=new SharedValue_UseThreadLocal();
		thread2.start();
		SharedValue_UseThreadLocal thread3=new SharedValue_UseThreadLocal();
		thread3.start();
	
	}

	@Override
	public void run() {
		
		Thread t=Thread.currentThread();
		long id=t.getId();
		
		for(long i=0; i<100; i++) {
			threadLocal.set(id); //update the value of the ThreadLocal.
			
			Sleep(10); //hold the execution for 10 milliseconds 
			if (id !=threadLocal.get()) {
				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());
		}
	}
}