下面是关于定时器的代码:
- public class My extends Thread {
- public static void main(String args[]) throws Exception
- {
-
- Thread t1=new My();
- t1.start();
- }
- public void run()
- {
- while(true)
- {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("thread");
- }
- }
- }
复制代码 上面代码段,隔一秒输出一句thread。- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class My2 {
- public static void main(String args[]) throws Exception
- {
- ScheduledExecutorService se=Executors.newScheduledThreadPool(1);
- se.scheduleAtFixedRate(
- new Runnable(){
- public void run() {
- System.out.println("tread");
- }},
- 1,
- 1,
- TimeUnit.SECONDS);
- }
- }
复制代码 这段代码也是隔一秒输出一句 thread
同样都完成了一种功能,有什么区别,理解的不是很透彻
|