ThreadLocal Usage

ThreadLocal can be used if you want variable/object to be maintained till the end of thread execution.

 

public class ThreadLocalTest extends Thread {
    // Define/create thread local variable
    static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
    int serialNo;
    public ThreadLocalTest(int serialNo) {
        this.serialNo = serialNo;
    }
    public void run() {
        threadLocal.set( serialNo );
        System.out.println( “Thread name:”+ Thread.currentThread().getName() +“\tSerialNo:” + threadLocal.get() );
    }
    public static void main( String args[] ) {
        for ( int cnt = 0; cnt < 5; cnt++ ) {
            Thread t = new Thread( new ThreadLocalTest( cnt ), “Thread-“ + cnt );
            t.start();
        }
    }
}

 

Output:

Thread name:Thread-1 SerialNo:1

Thread name:Thread-3 SerialNo:3

Thread name:Thread-0 SerialNo:0

Thread name:Thread-2 SerialNo:2

Thread name:Thread-4 SerialNo:4

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: