我需要一些有关 isAlive()
和 join()
函数的帮助。我了解如何以以下形式实现 isAlive()
和 join()
:
public class mthread implements Runnable{
public void run(){
for (int i = 0; i <3; i++){
System.out.println("sleep.. " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread a1 = new Thread (new mthread());
Thread a2 = new Thread (new mthread());
Thread a3 = new Thread (new mthread());
a1.start();
a2.start();
a3.start();
System.out.println("a1.isAlive() = " + a1.isAlive());
System.out.println("a2.isAlive() = " + a2.isAlive());
System.out.println("a3.isAlive() = " + a3.isAlive());
try {
a1.join();
a2.join();
a3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("a1.isAlive() = " + a1.isAlive());
System.out.println("a2.isAlive() = " + a2.isAlive());
System.out.println("a3.isAlive() = " + a3.isAlive());
}
}
但是如果我想做这样的事情:
public class mthread implements Runnable{
public void run(){
for (int i = 0; i <3; i++){
System.out.println("sleep.. " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++){
new Thread (new mthread()).start();
}
for (int i = 0; i < 20; i++){
**System.out.println(i + " isAlive() = " + i.isAlive());**
}
try {
for (int i = 0; i < 20; i++){
**i.join();**
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 20; i++){
**System.out.println(i + " isAlive() = " + i.isAlive());**
}
}
}
当线程没有实名时,如何实现isAlive()
或join()
函数?
谢谢。
最佳答案
How do I implement isAlive() or join() function when there is no real name for Thread
你不能。 ; )当您不为变量分配某些内容时,您将永远失去对它的跟踪。 (从技术上讲,Thread
在这方面是一个 little 位 special。)
您可以将您的线程
放在 array 中跟踪它们。
Thread[] threads = new Thread[20];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new mthread());
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
System.out.println(i + " isAlive() = " + threads[i].isAlive());
}
try {
for (int i = 0; i < threads.length; i++){
threads[i].join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < threads.length; i++) {
System.out.println(i + " isAlive() = " + threads[i].isAlive());
}
作为旁注,Java 中的类名称按照惯例以大写字母开头。您的mthread
应该是MThread
。它也可能应该是 MRunnable
,因为它是 Runnable
,而不是 Thread
。
关于Java isAlive() 和 join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007027/