我想同时运行一些线程并在一段时间后停止它们。它是否正确? :
object = new MyClass(numberThreads, time);
object.start();
//wait in main thread
try {
object.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
现在在MyClass类我有:
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();
}
}
有时在所有线程被中断之后,似乎有些线程没有被启动,但是如果它们都在同一时间运行,那么每个人都应该执行,我做错了什么?
答案 0 :(得分:0)
object.join();
此代码将在主线程中等待完成MyClass线程。
然后在MyClass中你有一个循环
for (int i = 0; i < numberThreads; i++) {
secObj[i] = new SecondClass();
secObj[i].start();
}
此循环启动SecondClass的新线程,线程数= numberThreads 。
然后:
//wait
Thread.sleep(time);
如果睡眠时间太短 - 那么即使在某些SecondClass线程可能启动之前,MyClass也可能发送中断。
但是你打断了不同数量的线程&#34; par &#34;,我不知道你在哪里声明它:
for (int i = 0; i < par; i++) {
secObj[i].interrupt();
}
因此,您可以中断不同数量的线程。如果你在SecondClass中处理异常,那么它仍然可能在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