我需要有关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()函数?

谢谢。

最佳答案

没有线程的真实名称时,如何实现isAlive()或join()函数


你不能。 ; )当您不给变量赋值时,您将永远无法对其进行跟踪。 (从技术上讲,就此而言,Threadlittlespecial。)

您可以将Thread放在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 - Java isAlive()和join(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27007027/

10-12 14:39