//调用的工具 import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
public class Task3 {
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) { </span><span style="color: rgba(0, 128, 0, 1)">/</span><span style="color: rgba(0, 128, 0, 1)"> * Runnable:实现了Runnable接口,jdk就知道这个类是一个线程 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)"> Runnable runnable </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Runnable() { </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建 run 方法</span> <span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> run() { </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> task to run goes here</span> System.out.println("Hello, stranger"<span style="color: rgba(0, 0, 0, 1)">); } }; </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> ScheduledExecutorService:是从Java SE5的java.util.concurrent里, </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 做为并发工具类被引进的,这是最理想的定时任务实现方式。</span> ScheduledExecutorService service =<span style="color: rgba(0, 0, 0, 1)"> Executors .newSingleThreadScheduledExecutor(); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 10:秒 5:秒 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 第一次执行的时间为10秒,然后每隔五秒执行一次</span> service.scheduleAtFixedRate(runnable, 10, 5<span style="color: rgba(0, 0, 0, 1)">, TimeUnit.SECONDS); }
}
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/h6javajc/9642.html