wait と notiry を使う
1 |
private void cancel() {
synchronized(this){
isCancel = true;
//止まっているスレッドを復帰させる
this.notify();
}
}
@Override
public void run() {
try {
synchronized(this){
// notify か 時間が来るまで待機
this.wait(delay);
if (isCancel){
return;
}
}
this.runnable.run();
} catch (Exception e) {
}
}
} |
sleep と interrupt を使う
1 |
private void cancel() {
isCancel = true;
//スレッドに割り込みを入れる
interrupt();
}
@Override
public void run() {
try {
//割り込まれるか時間が来るまで待機
Thread.sleep(delay);
} catch (Exception e){}
if (!isCancel){
this.runnable.run();
}
} |
カウントダウンタイマーのサンプル
wait と notify を使う
1 |
public class test {
public static void main(String[] args){
RunTimer timer = new RunTimer();
Runnable run = new Runnable(){
public void run(){
System.out.println("run");
}
};
timer.cancel();
timer.start(run, 1000);
}
}
class RunTimer {
private LocalThread current;
public void start(Runnable runnable, long delay) {
current = new LocalThread(runnable, delay);
current.start();
}
// 最後にstartした処理のみキャンセル可能
public void cancel() {
if (current != null) {
current.cancel();
}
}
private class LocalThread extends Thread {
private Runnable runnable;
private long delay;
private boolean isCancel;
private LocalThread(Runnable runnable, long delay) {
this.runnable = runnable;
this.delay = delay;
this.isCancel = false;
}
private void cancel() {
synchronized(this){
isCancel = true;
this.notify();
}
}
@Override
public void run() {
try {
synchronized(this){
this.wait(delay);
if (isCancel){
return;
}
}
this.runnable.run();
} catch (Exception e) {
}
}
}
} |
sleep と interrupt を使う
1 |
public class test {
public static void main(String[] args){
RunTimer timer = new RunTimer();
Runnable run = new Runnable(){
public void run(){
System.out.println("run");
}
};
timer.cancel();
timer.start(run, 1000);
}
}
class RunTimer {
private LocalThread current;
public void start(Runnable runnable, long delay) {
current = new LocalThread(runnable, delay);
current.start();
}
// 最後にstartした処理のみキャンセル可能
public void cancel() {
if (current != null) {
current.cancel();
}
}
private class LocalThread extends Thread {
private Runnable runnable;
private long delay;
private boolean isCancel;
private LocalThread(Runnable runnable, long delay) {
this.runnable = runnable;
this.delay = delay;
this.isCancel = false;
}
private void cancel() {
isCancel = true;
interrupt();
}
@Override
public void run() {
try {
Thread.sleep(delay);
} catch (Exception e){}
if (!isCancel){
this.runnable.run();
}
}
}
} |
[通知用URL]
Tweet
最終更新時間:2010年12月29日 16時39分30秒