Let's look at a piece of code:
public static void Main (string[] args) {
new Timer (). Schedule (new TimerTask () {
@Override public
void Run () {
System.out.println ("Sunshine Cockroach");
}
}, 5000);
int i = 0;
while (true) {
System.out.println (i++);
try {
thread.sleep (1000);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
}}
Modify the above code as follows:
New Timer (). Schedule (new TimerTask () {
@Override public
void Run () {
System.out.println ("Sunshine Cockroach");
}
}, 2000, 3000);
The timer timer starts executing the Run method after 2000ms and repeats every 3000ms.
If there is a demand, 1s, 2s, 1s, 2s ... Execute the code in the timer separately (even seconds and odd seconds to perform different timers respectively), how do we implement (s on behalf of the second)
Implementation Mode one:
public static void Main (string[] args) {
new Timer (). Schedule (new TimerTask () {
@Override public
void Run () {
System.out.println ("Sunshine cockroach 2 Seconds");
New Timer (). Schedule (new TimerTask () {
@Override public
void Run () {
System.out.println ("Sunshine cockroach 4 Seconds")
},
1000);
}}
, 1000;
int i = 0;
while (true) {
System.out.println (i++);
try {
thread.sleep (1000);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
}}