使用运行方法启动一个watcher Thread

Use the run method to start a watcher Thread

我有一个

 ThreadPoolExecutor cachedPool = (ThreadPoolExecutor)Executors.newCachedThreadPool();

cachededPool 必须在主要 SimController class 中执行以下功能。

运行 观察线程的方法。每秒一次,检查并调用函数。

public void run(){
            if(m.isChanged()){
                m.toString();
            }                   
    }

但是它只执行一次运行方法。 我怎样才能做到每秒 运行 并创建一个观察者。

您可以按照 Peter Lawrey 在评论中的建议使用 ScheduledExecutorService.scheduleAtFixedRate(),或者您可以执行以下操作:

public void run() throws InterruptedException {
    for( ;; ) {
        if( m.isChanged() ) //hopefully m is thread-safe
            m.toString();   //hopefully something more meaningful here
        Thread.sleep( 1000 ); //1000 milliseconds is one second.
    }
}

注意:如果你的run()方法不能抛出InterruptedException,那么你需要处理Thread.sleep()可能抛出的InterruptedException。一种快速而肮脏的方法是只说 try{ ... } catch( InterruptedException e ) { throw new AssertionError( e ); } 但如果你想以正确的方式做到这一点,那么一定要阅读这个:Handling InterruptedException in Java

ScheduledExecutorService 使这个变得非常简单,因为这个例子每秒打印一次日期,显示:

public class MonitorService {
    public static void main(String[] a) throws Exception {
        ScheduledExecutorService service = 
                Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(() -> {
            System.out.println(LocalDateTime.now());
        }, 0, 1, TimeUnit.SECONDS);
    }
}

如果您的系统中有多个作业要调度,您可能希望在所有任务之间共享调度的执行程序服务以提高效率。

如果您使用的是 Spring,那么您还可以使用 @Scheduled task 而不是 运行 计划任务的方法。

@Component
@EnableScheduling
public class TestClass {
    @Scheduled(fixedRate= 1000 , initialDelay = 18000)
    public void TestMethod(){
       // Do Something

    } }