6 回答

TA贡献1828条经验 获得超6个赞
贴个代码吧,公共开关的思路。
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;
}
}
}
仅供参考
添加回答
举报