java - 不知如何退出这样的 for 循环?
黄舟
黄舟 2017-04-18 09:45:48
0
8
599
for(Object i: items){
    new Task(new Callback(){

        @Override
        public void finish() {
            //todo
        }
    }).run();
}

就以上代码,如何在finish方法中退出for循环,求教!

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(8)
洪涛

给里外层设置个公用开关,里层跳出后,外层也中断.

阿神

贴个代码吧,公共开关的思路。

public class TestMain {
    public volatile static boolean flag = false;

    public static void main(String[] args) {

        for (int index = 0; index < 100; index++) {
            if (flag) {
                System.out.println("我要退出了,这时候i是:" + index);
                break;
            } else {
                Task task = new Task(index);
                Thread thread = new Thread(task);
                thread.setName("线程"+index);
                thread.start();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
public class Task implements Runnable{
    private Integer i;
    Task(Integer i){
        this.i = i;
    }
    public void run() {
        System.out.println("我是"+Thread.currentThread().getName());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(i == 10){
            TestMain.flag = true;
        }
    }
    
}

仅供参考

阿神

不是同步的,没办法从finish函数中直接中断。你可以设置个标记或是其他什么方法了

阿神

是同步的,但没法直接中断。

伊谢尔伦

赞成楼上的思路 用公共开关

Peter_Zhu

自定义个异常抛出

阿神

赞成二次元李健的回答,可以考虑设置标志变量

刘奇

你这么写应该是对CyclicBarrier不熟悉吧

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!