Android循环中的线程

时间:2016-02-04 15:11:12

标签: android multithreading for-loop

我有一个for循环,其中包含一个线程。代码可以工作,但参数没有正确传递给函数。你能救我吗?

for(i= 1 ;i < 30; i++) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            example_function(i);
        }
    };

    thread.start();
}

3 个答案:

答案 0 :(得分:2)

这段代码开始时看起来很可疑,但你应该在线程中使用Runnable

如果您添加如下所示的MyRunnable类,则会出现您想要的内容:

private class MyRunnable implements Runnable {
    private int i;
    public MyRunnable(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        example_function(i);
    }
}

然后你的for循环变为:

for(i= 1 ;i < 30; i++) {
    new Thread(new MyRunnable(i)).start();
}

这些数字仍然可以按顺序打印,但每次只会打印一次。

答案 1 :(得分:1)

使用参数

扩展Thread
class IntThread extends Thread {

    private int i;

    public IntThread( int i ) {
       this.i = i;
    }

    @Override
    public void run() {
        example_function( this.i );
    }
}

然后执行:

    for(int i= 1 ;i < 30; i++) {
        new IntThread( i ).start();
    }

答案 2 :(得分:0)

你应该在你的线程中添加一个字段int j,并在运行你的线程之前用thread.j = i初始化它

for(i= 1 ;i < 30; i++) {
Thread thread = new Thread() {
    final int j;
    @Override
    public void run() {
        example_function(j);
    }
 };
thread.j = i;
thread.start();
}