在Example里面加 new Timer().schedule(new TimeTask{ public void run(){ doLoop(); } },60000);
更正一下,应该这样 public class Example extends Thread{ public Example(){ start(); } public void run(){ try{ doloop(); }catch(InterruptedException e){ System.out.println("Stop"); } } public static void main(String[] args){ Example ex = new Example(); new Timer().schedule(new TimeTask{ public void run(){ ex.interrupt(); } },60000); } }
Timer里面的类应该是TimerTask doloop的方法内容我把它给省略了
import java.util.Timer; import java.util.TimerTask; public class Example { Timer timer = new Timer(); int seconds; Example(int seconds) { this.seconds = seconds; } public void doLoop() { } public void start() { doLoop(); timer.schedule(new TimerTask() { public void run() { timer.cancel(); } }, seconds * 1000); } public static void main(String[] args) { Example example = new Example(60); example.start(); }}
public static void main(String[] args) throws Exception{ Example ex = new Example();//example类要继承Thread ex.start();//开一个线程 sleep(60000); System.exit(0);//你可以试一下! }
new Timer().schedule(new TimeTask{
public void run(){
doLoop();
}
},60000);
public class Example extends Thread{
public Example(){
start();
}
public void run(){
try{
doloop();
}catch(InterruptedException e){
System.out.println("Stop");
}
}
public static void main(String[] args){
Example ex = new Example();
new Timer().schedule(new TimeTask{
public void run(){
ex.interrupt();
}
},60000);
}
}
doloop的方法内容我把它给省略了
import java.util.TimerTask;
public class Example {
Timer timer = new Timer();
int seconds;
Example(int seconds) {
this.seconds = seconds;
}
public void doLoop() { }
public void start() {
doLoop();
timer.schedule(new TimerTask() {
public void run() {
timer.cancel();
}
}, seconds * 1000); }
public static void main(String[] args) {
Example example = new Example(60);
example.start();
}}
调用一个线程,一分钟之后把设为true
开始循环,判断为true时跳出
Example ex = new Example();//example类要继承Thread
ex.start();//开一个线程
sleep(60000);
System.exit(0);//你可以试一下!
}