Reputation: 113
I'm currently learning Java and just came to the topic of threads. I'm trying to develop a single program which prints some letters from input, but i have encountered problem with terminating the threads and frankly don't know what to do next. Here's my code:
public class Main {
public static void main(String[] args) throws InterruptedException {
Letters letters = new Letters("ABCD");
for (Thread t : letters.getThreads()) System.out.println(t.getName());
for (Thread t : letters.getThreads()) t.start();
Thread.sleep(5000);
for (Thread t : letters.getThreads()) t.interrupt();
System.out.println("\nProgramme has finished working");
}
}
I' trying to achieve printing seperate letters from this String each from its own seperate thread for 5 seconds in 1 second intervals, during which the main thread will be waiting. After this time I want all of these threads to terminate via usage of interrupt() method.
public class Letters {
private String input;
char[] signs=null;
public Letters(String input) {
this.input = input;
signs= new char[input.length()];
for (int i = 0; i < input.length(); i++) {
signs[i] = input.charAt(i);
}
}
MyThread[] getThreads() {
MyThread thread_arr[]=new MyThread[signs.length];
for (int i=0; i<signs.length;i++)
{thread_arr[i]=new MyThread(signs[i]);
}
return thread_arr;}
}
public class MyThread extends Thread {
private char out;
public MyThread(char out) {
super();
this.out = out;
this.setName("Thread "+out);
}
public void run() {
while(!Thread.currentThread().isInterrupted())
{
try {
System.out.print(out);
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
I'm aware that according to official Java Tutorial about Concurrency, the return alone should be sufficient to terminate shown thread, however its not working for me. The threads just carry on doing their tasks. Any help would be greatly appreciated.
Upvotes: 1
Views: 150
Reputation: 25573
Each call to letters.getThreads()
creates a new array of threads, so your calls to Thread.start()
and Thread.interrupt()
are calling completely different sets of threads.
Upvotes: 4