51,411
社区成员
发帖
与我相关
我的任务
分享
package com.xxx.ut;
import java.io.IOException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author x
*/
public class Watch {
private static ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
private volatile int counter = 0;
public static void main(String[] args) throws InterruptedException, IOException {
Watch watch = new Watch();
startWatch(watch);
//mock value change: 其他的逻辑修改了变量
AtomicInteger value = new AtomicInteger(0);
scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
watch.setCounter(value.getAndIncrement());
}, 3, 2, TimeUnit.SECONDS);
System.in.read();
}
private static void startWatch(Watch watch) {
new Thread(() -> {
ThreadLocal<Integer> localCounter = ThreadLocal.withInitial(() -> watch.getCounter());
for (; ; ) {
if (localCounter.get() != watch.getCounter()) {
System.out.println("counter changed : " + watch.getCounter());
localCounter.set(watch.getCounter());
}
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
}