62,623
社区成员
发帖
与我相关
我的任务
分享
import java.util.logging.Level;
import java.util.logging.Logger;
class MainThread {
public void good(){
//启动一个线程执行F()方法
Worker w = new Worker("运行F()", this);
w.start();
//等等10秒
synchronized (this) {
try {
wait(10000);
} catch (InterruptedException ex) {
Logger.getLogger(MainThread.class.getName()).log(Level.SEVERE, null, ex);
}
w.shutdown();
}
}
public void F() throws InterruptedException{
System.out.println("玩游戏");
//做一些事情
//如果会InterruptedException异常
//Thread.sleep(1000000);
}
private class Worker extends Thread {
private final MainThread mt;
public Worker(String name, MainThread mt) {
super("线程名字是" + name);
this.mt = mt;
}
public final void shutdown() {
interrupt();
}
@Override
public final void run() {
try {
mt.F();
} catch (InterruptedException ex) {
//Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//唤醒主线程。
synchronized(mt) {
mt.notify();
}
}
}
}
public static void main(String[] args) {
MainThread mt = new MainThread();
mt.good();
}
}