如何同时运行多个“ for”循环?

时间:2020-03-30 12:27:47

标签: java android

所以这是我有史以来第一个在android上的应用,在我的一种方法中,我需要4个for循环才能同时运行。问题是实际上他们一个接一个地运行,而不是同时运行。这是我的方法: 编辑:

public void play() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                    for (int i = 0; i < 8; i++) {
                        if (buttonArray0[i].isChecked()) { //Si le bouton d'indice i est actif, le son est joué.
                            soundPool.play(bongo, 1, 1, 1, 0, 1);
                        }
                    }
                    sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();

    Thread thread2 = new Thread() {
        @Override
        public void run() {
            try {
                    for (int i = 0; i < 8; i++) {
                        if (buttonArray1[i].isChecked()) { //Si le bouton d'indice i est actif, le son est joué.
                            soundPool.play(caisse_claire, 1, 1, 1, 0, 1);
                        }
                    }
                    sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread2.start();

    Thread thread3 = new Thread() {
        @Override
        public void run() {
            try {
                    for (int i = 0; i < 8; i++) {
                        if (buttonArray2[i].isChecked()) { //Si le bouton d'indice i est actif, le son est joué.
                            soundPool.play(grosse_caisse, 1, 1, 1, 0, 1);
                        }
                    }
                    sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread3.start();

    Thread thread4 = new Thread() {
        @Override
        public void run() {
            try {
                    for (int i = 0; i < 8; i++) {
                        if (buttonArray3[i].isChecked()) { //Si le bouton d'indice i est actif, le son est joué.
                            soundPool.play(cymbale, 1, 1, 1, 0, 1);
                        }
                    sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread4.start();
}

我进行了一些研究,我想我知道您需要Java程序中的线程才能同时运行许多事情,但是即使尝试了几种方法,我也不知道如何在我的情况下实现线程我在互联网上找到的东西。我需要一些建议,以便能够全面了解它的工作方式以及如何针对我的情况进行操作。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

您应该创建一个多线程程序

此方法将使该线程休眠几秒钟,但除非执行此for循环,否则该线程不会进入另一个for循环。

Thread.sleep(1000);

尝试一下

Thread thread = new Thread() {
@Override
public void run() {
    try {
        while(true) {
            //add your for loop here
            sleep(1000);
            handler.post(this);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
  }
};

thread.start();

如果您在for循环中使用不同的计算方法,则应创建多次。