一段时间后运行并中断线程



我想同时运行一些线程,并在一段时间后全部停止它们。它是否正确?:

 object = new MyClass(numberThreads, time);
 object.start();
//wait in main thread
    try {
        object.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

现在我有:

public void run() {
    SecondClass[] secObj= new SecondClass[numberThreads];
    //start all
    for (int i = 0; i < numberThreads; i++) {
        secObj[i] = new SecondClass();
        secObj[i].start();
    }
    try {
        //wait
        Thread.sleep(time);
    } catch (InterruptedException e) {
        System.out.println("end");
    }
        //Interrupt all
        for (int i = 0; i < par; i++) {
            secObj[i].interrupt();
        }
}

有时在所有线程被中断后,似乎没有启动其中一些线程,但是如果它们都同时运行,每个人都应该执行,我在做什么错?

object.join();

此代码将在主线程中等待MyClass线程的完成。

然后在myclass中您有一个循环

for (int i = 0; i < numberThreads; i++) {
    secObj[i] = new SecondClass();
    secObj[i].start();
}

此循环启动了第二类的新线程,线程的数量= numberThreads

然后:

//wait
Thread.sleep(time);

如果睡眠时间太小 - 那么MyClass甚至可能在某些第二类线程启动之前发送中断。

但是您中断了不同数量的线程" PAR ",我看不到您在哪里声明它:

for (int i = 0; i < par; i++) {
    secObj[i].interrupt();
}

因此,您中断不同数量的线程。如果您在第二阶段中处理异常,则在myclass完成后仍可以工作。

我的示例:

public class MyClass extends Thread {
private int numberThreads;
private int time;
static class SecondClass extends Thread{
    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("interrupted");
        }
        System.out.println("finished");
    }
}
MyClass(int numberThreads, int time){
    this.numberThreads = numberThreads;
    this.time = time;
}
public static void main(String[] args) {
    MyClass object = new MyClass(6, 1000);
    object.start();
    //wait in main thread
    try {
        object.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Main thread is finished");
}
public void run() {
    SecondClass[] secObj= new SecondClass[numberThreads];
    //start all
    for (int i = 0; i < numberThreads; i++) {
        secObj[i] = new SecondClass();
        secObj[i].start();
    }
    try {
        //wait
        Thread.sleep(time);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //Interrupt all
    for (int i = 0; i < numberThreads; i++) {
        secObj[i].interrupt();
    }
    System.out.println("MyClass is finished");
}
}

输出:

interrupted
interrupted
finished
finished
interrupted
finished
interrupted
finished
interrupted
finished
MyClass is finished
interrupted
finished
Main thread is finished

最新更新