62,614
社区成员
发帖
与我相关
我的任务
分享
System.out.println("I'm still running...");
public static void g(NewInterface obj) throws Exception {
Thread t = new Thread(obj);
t.start();
t.join(3 * 1000);
if (!obj.isFinished()) {
obj.interrupt();
throw new Exception();
}
}
public interface NewInterface extends Runnable {
boolean isFinished();
void interrupt();
}
/**
* @author bzwm
*
*/
public class MethodTimeOut {
public static void main(String args[]){
Executer e = new Executer("obj->bzwm");
e.start();
try {
e.join(1000);
} catch (InterruptedException e1) {
System.out.println(e.toString());
}
e.interrupt();
System.out.println(e.isOver());
}
}
class Executer extends Thread{
private Object obj = null;
private boolean isOver = false;
public Executer(Object o){
obj = o;
}
public void run(){
doSomething();
}
private void doSomething(){
System.out.println("Start do something with " + obj);
try {
sleep(1500);
} catch (InterruptedException e) {
}
System.out.println("do something with " + obj + " over");
isOver = true;
}
public boolean isOver(){
return isOver;
}
}
public static void main(String[] args) {
long past = new Date().getTime();
System.out.println("wait 10 sec....");
while (true) {
if (new Date().getTime() - past > 10000) {
break;
}
}
System.out.println("10 sec is past");
}
public abstract class TimedTask implements TimedRunnable {
private boolean expired;
public synchronized void expire() {
expired = true;
}
}
public interface TimedRunnable extends Runnable {
void expire();
}
public class TimedTaskExecuter {
private static class ExpiringThread extends Thread {
TimedRunnable timed;
long expired;
ExpiringThread(TimedRunnable task, long expiredTime) {
timed = task;
expired = expiredTime;
}
public void run() {
try {
Thread.sleep(expired);
} catch (InterruptedException e) { e.printStackTrace(); }
timed.expire();
}
}
public static void execute(TimedRunnable task, long expiredTime) {
new Thread(task).start();
new ExpiringThread(task, expiredTime).start();
}
}
public class ExpiringTest implements TimedRunnable {
private boolean expired;
public void run() {
while (!expired) {
try {
System.out.println("I'm still running...");
Thread.sleep(100);
} catch (InterruptedException e) { e.printStackTrace(); }
}
System.out.println("expired!");
}
public synchronized void expire() {
expired = true;
}
public static void main(String[] args) {
TimedTaskExecuter.execute(new ExpiringTest(), 1000);
}
}