您可以使用Java API它,Java提供ScheduledThreadPoolExecutor這將讓你:
- 創建線程池(併爲您提供多少個線程要你控制在JVM中用於此目的, JVM管理該線程池)。
- 公開方法來指定任務的時間表。
我爲您提供了一個示例實現,我添加了代碼註釋以便您理解,您還可以參考聯機文檔或示例。如有任何問題,請隨時通知我。
順便說一句,如果你想獲得結果從線程的執行當時不是使用Runnable
可以使用Callable
接口,它可以讓你返回的東西,和ScheduledThreadPoolExecutor
重載了它讓你通過一個Callable
對象方法。
示例代碼:
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolExecutorExample {
private final static int MAX_NUMBER_OF_THREADS = 2;
private final static int EXECUTION_SCHEDULE_PERIOD_IN_SECONDS = 5;
private final static int INITAL_DELAY_IN_SECONDS = 0;
// set maximum number of threads as per your requirement/performance tuning, for testing set it to "2" and to have better feel.
private final static ScheduledThreadPoolExecutor SCHEDULED_THREAD_POOL_EXECUTOR = new ScheduledThreadPoolExecutor(MAX_NUMBER_OF_THREADS);
public static void main(String[] args) {
scheduleTask(new MyRunnableTask("google1.com", 80)); // if you want more fields to set then either use constructor or have setter methods.
scheduleTask(new MyRunnableTask("google2.com", 80)); // if you want more fields to set then either use constructor or have setter methods.
scheduleTask(new MyRunnableTask("google3.com", 80)); // if you want more fields to set then either use constructor or have setter methods.
scheduleTask(new MyRunnableTask("google4.com", 80)); // if you want more fields to set then either use constructor or have setter methods.
}
private static void scheduleTask(Runnable runnable) {
SCHEDULED_THREAD_POOL_EXECUTOR.scheduleAtFixedRate(runnable, INITAL_DELAY_IN_SECONDS, EXECUTION_SCHEDULE_PERIOD_IN_SECONDS, TimeUnit.SECONDS);
}
}
的Runnable:
import java.util.Date;
public class MyRunnableTask implements Runnable {
private String hostName;
private int port;
MyRunnableTask(String _hostName, int _port){
this.hostName = _hostName;
this.port = _port;
}
@Override
public void run() {
System.out.println(this.hostName + ":: I am getting executed: " + this.hashCode() + " | " + Thread.currentThread().getId() + " | " + new Date());
// implement your socket programming code here
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
如果你是「新」這兩個概念,這是不是你應該工作。您需要從每個傳感器的基礎知識開始,然後將它們組合在一起 – CraigR8806
您對每個傳感器/設備的溫度做什麼? – LoganMzz
把它放到共享陣列和檢索完成的(所有設備)之後將陣列插入到PostgreSQL數據庫 – Dmitry