マルチスレッド02-タイマ
7686 ワード
ケース1
1秒間隔後にtaskタスクを実行
package org.lkl.timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerFoo {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Liaokailin.");
}
};
/**
* 1 task
*/
new Timer().schedule(task, 1000) ;
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ケース2
1秒間隔後に初めてtaskが実行され、その後2秒間隔でtaskが実行される
package org.lkl.timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerFoo {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Liaokailin.");
}
};
/**
* 1 task , 2 task
*/
new Timer().schedule(task, 1000,2000) ;
/**
* , 1
*/
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ケース3
2秒間隔以降にtaskを1回実行し、その後4秒間隔でtaskを1回実行する
package org.lkl.timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerFoo {
static int flag = 0 ;
public static void main(String[] args) {
class MyTimerTask extends TimerTask{
int count = ++flag%2 ;
//flag = flag%2 ;
@Override
public void run() {
System.out.println("Liaokailin.");
new Timer().schedule(new MyTimerTask() , 2000+2000*count) ;
}
}
/**
* 2 task , 4 task
*/
new Timer().schedule(new MyTimerTask() , 2000) ;
/**
* , 1
*/
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}