Java Thread - 如何使用CyclicBarrier和TimerTask
我們想知道如何使用CyclicBarrier和TimerTask。
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CyclicBarrier;
public class Main {
static CyclicBarrier cb;
public static void main(String[] args) {
cb = new CyclicBarrier(2);
Timer t = new Timer();
t.schedule(new MyTimerTask(cb), 1000, 1000);
while (true) {
try {
cb.await();
} catch (Exception e) {
}
System.out.println("main");
}
}
}
class MyTimerTask extends TimerTask {
private CyclicBarrier cb;
public MyTimerTask(CyclicBarrier c) {
cb = c;
}
public void run() {
try {
cb.await();
} catch (Exception e) {
}
}
}
運(yùn)行結(jié)果如下: