如题,有时候我们需要在Main函数中写测试代码,并且需要在异步线程中执行任务,任务执行完之后才退出主线程,如何做到的呢,请看如下代码:
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("-------work------start---------");
LockHandler mHandler=new LockHandler();
Thread mThread=new Thread(new WorkRunnable(mHandler));
mThread.setDaemon(true);
mThread.start();
mHandler.waitForDebug();
System.out.println("-------work------end---------");
}
public static class WorkRunnable implements Runnable
{
public LockHandler mHandler;
public WorkRunnable(LockHandler mHandler)
{
this.mHandler = mHandler;
}
public void run() {
//TODO
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-------我在异步线程中睡了五秒---------");
mHandler.notifytForDebug();
}
}
public static class LockHandler
{
public synchronized void waitForDebug()
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void notifytForDebug()
{
this.notifyAll();
}
}
}
执行结果:
-------work------start---------
-------我在异步线程中睡了五秒---------
-------work------end---------
只需要重写WorkRunnable类的run()方法,so easy !