1 public class Demo01 {
 2     static long count = 0;
 3     public static void main(String[] args) {
 4         Runnable runnable = new Runnable() {
 5             @Override
 6             public void run() {
 7                 while (true) {
 8                     try {
 9                         Thread.sleep(1000);
10                         count++;
11                         System.out.println(count);
12                     } catch (Exception e) {
13                         // TODO: handle exception
14                     }
15                 }
16             }
17         };
18         Thread thread = new Thread(runnable);
19         thread.start();
20     }
21 }
Thread线程定时任务
 1 /**
 2  * 使用TimerTask类实现定时任务
 3 */
 4 public class Demo02 {
 5     static long count = 0;
 6
 7     public static void main(String[] args) {
 8         TimerTask timerTask = new TimerTask() {
 9
10             @Override
11             public void run() {
12                 count++;
13                 System.out.println(count);
14             }
15         };
16         Timer timer = new Timer();
17         // 天数
18         long delay = 0;
19         // 秒数
20         long period = 1000;
21         timer.scheduleAtFixedRate(timerTask, delay, period);
22     }
23
24 }
TimerTask
 1 public class Demo003 {
 2     public static void main(String[] args) {
 3         Runnable runnable = new Runnable() {
 4             public void run() {
 5                 // task to run goes here
 6                 System.out.println("Hello !!");
 7             }
 8         };
 9         ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
10         // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
11         service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
12     }
13 }
线程池定时ScheduledExecutorService
12-29 15:26
查看更多