public class Letters extends Thread implements Iterable<Thread>
{
private String chars;
private Thread[] threads;
int index = 0;
public Letters(String chars)
{
this.chars = chars;
this.threads = new Thread[chars.length()];
for (int i = 0; i < threads.length; i++)
{
int finalI = i;
Thread thread = new Thread()
{
@Override
public void run()
{
while (!Letters.this.isInterrupted())
{
System.out.print(chars.charAt(finalI));
try
{
Thread.sleep((int) (Math.random() * 2000));
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
}
};
threads[finalI] = thread;
}
}
@Override
public void run()
{
for (Thread thread : threads)
{
thread.start();
}
while (true)
{
if (this.isInterrupted())
return;
}
}
Iterator<Thread> threadsIterator = new Iterator<Thread>()
{
@Override
public boolean hasNext()
{
return index < threads.length;
}
@Override
public Thread next()
{
return threads[index++];
}
};
@Override
public Iterator iterator()
{
return threadsIterator;
}
}
The Letters class object is created in main method and there is interrupted:
public static void main(String[] args)
{
Letters letters = new Letters("ABCD");
for (Thread t : letters)
System.out.println(t.getName() + " starting");
letters.start();
try
{
Thread.sleep(5000);
}
catch(InterruptedException ignore)
{
}
letters.interrupt();
System.out.println("\nProgram completed.");
}
My question is about this part:
@Override
public void run()
{
for (Thread thread : threads)
{
thread.start();
}
while (true)
{
if (this.isInterrupted())
return;
}
}
Why if i use Thread.interrupted() instead of isInterrupted() it doesn't intterupt the parent threads that was started by this thread? In Java, how are sub-threads closed when the parent thread finishes its work?