简体   繁体   中英

Terminating Java threads

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.

每次对letters.getThreads()调用都会创建一个新的线程数组,因此您对Thread.start()Thread.interrupt()的调用正在调用完全不同的线程集。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM