I'm trying to add 10 threads to a set and name them sequentially. But when I debug to see the set, threads are not stored in sequential order. Can someone tell what I am doing wrong?
Set<Thread> allThreads = new HashSet<Thread>();
final DemoClass demo = new DemoClass();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
demo.getName();
} catch (InterruptedException ie) {
System.out.println("We have a problem");
}
}
});
thread.setName("Thread_" + (i + 1));
allThreads.add(thread);
}
for (Thread t : allThreads) {
t.start();
}
for (Thread t : allThreads) {
t.join();
}
}
When I see allThreads, the threads are jumbled everytime .