Java如何处理while循环

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class TaskLoop {

private final AtomicBoolean enableLoop = new AtomicBoolean(true);

private final AtomicInteger count = new AtomicInteger(1);

public void start() {
while (enableLoop.get()) {
System.out.println("count: " + count);
int i = count.getAndIncrement();
if (i == 5) {
stop();
}
if (Thread.currentThread().isInterrupted()) {
break;
}
}
}

public void stop() {
enableLoop.compareAndExchange(true, false);
}

public static void main(String[] args) {
TaskLoop taskLoop = new TaskLoop();
taskLoop.start();

}
}