I wrote a small program where i am storing the thread name in class level field and also printing it.
public class ThreadClass implements Runnable {
private String threadName = null;
@Override
public void run() {
System.out.println(" thread name " + threadName);
System.out.println(" current thread >>>>>> "
+ Thread.currentThread().getName());
threadName = Thread.currentThread().getName();
}
}
I wrote a test class where i created 10 threads and started them.
public class ThreadController {
public static void main(String[] args) {
ThreadClass threadClass = new ThreadClass();
Thread t1 = new Thread(threadClass, "T1");
Thread t2 = new Thread(threadClass, "T2");
Thread t3 = new Thread(threadClass, "T3");
Thread t4 = new Thread(threadClass, "T4");
Thread t5 = new Thread(threadClass, "T5");
Thread t6 = new Thread(threadClass, "T6");
Thread t7 = new Thread(threadClass, "T7");
Thread t8 = new Thread(threadClass, "T8");
Thread t9 = new Thread(threadClass, "T9");
Thread t10 = new Thread(threadClass, "T10");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
I am getting following output.
thread name null
thread name null
thread name null
current thread >>>>>> T1
current thread >>>>>> T6
current thread >>>>>> T2
thread name T2
thread name T2
thread name null
thread name null
thread name null
current thread >>>>>> T4
current thread >>>>>> T7
current thread >>>>>> T8
current thread >>>>>> T9
thread name T1
current thread >>>>>> T5
thread name T1
current thread >>>>>> T3
current thread >>>>>> T10
My doubt is if every thread creates a local copy of field variables then why i am not always getting thread name as null. Sorry if it sounds like a silly question but i am trying to learn threads.