其他线程完成后Java再次运行线程

弗里安

如何在其他线程完成后运行线程,假设我有 3 个 java 类(Cls1 和 Cls2 实现了可运行,我使用 sleep 来知道首先运行哪些语句),这是我的代码:

public class Master {
    @SuppressWarnings("unused")
    public static void main(String[] args) {
        //loop1
        for(int i=1; i<=2; i++) {
            Cls1 c1 = new Cls1();
        }

        //Here i want to wait until the thread loop1 is finished, what to do?

        //loop2
        for(int j=1; j<=2; j++) {
            Cls2 c2 = new Cls2();
        }
    }
}

public class Cls1 implements Runnable{
    Thread myThread;
    Cls1() {
        myThread = new Thread(this, "");
        myThread.start();       
    }

    @Override
    public void run() {
        System.out.println("hello1");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("hello2");
    }
}

public class Cls2 implements Runnable{
    Thread myThread;
    Cls2() {
        myThread = new Thread(this, "");
        myThread.start();
    }

    @Override
    public void run() {
        System.out.println("hello3");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("hello4");
    }
}

这是输出我的代码:hello1 hello1 hello3 hello3 hello2 hello2 hello4 hello4

这是我期望的输出:hello1 hello1 hello2 hello2 hello3 hello3 hello4 hello4

我应该怎么办 ?

莫里斯·佩里

你可以尝试这样的事情:

@SuppressWarnings("unused")
public static void main(String[] args) {
    Thread threads[] = new Thread[2];
    //loop1
    for(int i=1; i<=2; i++) {
        threads[i-1] = new Cls1();
    }

    for (Thread thread: threads) {
        thread.join();
    }

    //loop2
    for(int j=1; j<=2; j++) {
        Cls2 c2 = new Cls2();
    }
}

更新:使 Cls1 成为 Thread 的子类:

public class Cls1 extends Thread {
    Cls1() {
        start();       
    }

    @Override
    public void run() {
        System.out.println("hello1");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("hello2");
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章