1 package com.thread.test.thread;
2 import java.util.Timer;
3 import java.util.TimerTask;
4 import java.util.concurrent.*;
5 import java.util.concurrent.locks.ReentrantLock;
6
7
38 public class MyExecutor {
39 public static void main(String[] args) {
40 testTimer();
41 }
42
43 public static void testTimer(){
44 new Timer().schedule(new MyTimerTask(), 2000, 5000);
45 }
46
47 public static void testExecutors(){
48 MyERunnable mer = new MyERunnable(5);
49
50
51 ScheduledExecutorService es = Executors.newScheduledThreadPool(2);
52 es.schedule(mer, 10000, TimeUnit.SECONDS.MILLISECONDS);
53 es.scheduleAtFixedRate(mer, 2, 10, TimeUnit.SECONDS);
54 es.scheduleWithFixedDelay(mer, 1, 5, TimeUnit.SECONDS);
55 es.shutdown();
56 }
57 }
58
59 class MyERunnable implements Runnable{
60 private int num = 0;
61 MyERunnable(int num){
62 this.num = num;
63 }
64 public void run() {
65 ReentrantLock lock = new ReentrantLock();
66 try{
67 lock.lock();
68 for (int i = 0; i < num; i++) {
69 System.out.println("current thread: " + Thread.currentThread().getName() + " num--" + i);
70 Thread.sleep(1000);
71 }
72 }catch (Exception e){
73 e.printStackTrace();
74 }finally {
75 lock.unlock();
76 }
77 }
78 }
79
80 class MyTimerTask extends TimerTask{
81
82 @Override
83 public void run() {
84 System.out.println("timer task");
85 }
86 }
项目地址:github.com/windwant/wi…