【发布时间】:2019-11-28 23:15:05
【问题描述】:
我有一个实现可运行的类 ABC。 ABC 有多个线程在运行。在每个线程中我想安排一个 TimerTask。在这个 TimerTask 块中调用的函数对于线程的变量需要是线程安全的。
public class ABC implements Runnable {
private int abc = 0;
public void run() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
this.someFunc();
}
}, 1000, 1000);
while (true) {
abc = (abc + 1) % 20;
}
}
void someFunc() {
abc--;
}
}
这个线程是安全的还是我需要使 someFunc() 成为一个同步函数?
【问题讨论】:
-
不。它不是。您不需要使
someFunc同步。如果您愿意,可以通过其他方式处理此问题(AtomicInteger等)。
标签: java multithreading timer thread-safety timertask