java线程池主线程等待子线程执行完成
public class Threads { static ExecutorService executorService = Executors . newFixedThreadPool ( 1 ) ;
***@SuppressWarnings ( “rawtypes” )
public static void main (String[] args ) throws InterruptedException , ExecutionException
{
SubThread thread = new SubThread () ;
// ();
Future future = executorService . submit (thread) ;
mainThreadOtherWork () ;
System . out . println ( “now
waiting sub thread done.” ) ;
future . get () ;
// try {
// ();
// } catch (InterruptedException e) {
// ();
// }
System . out . println ( “now
all done.” ) ;
executorService . shutdown () ;
} private static void mainThreadOtherWork ()
{
System . out . println ( “main
thread work start” ) ;
try {
Thread . sleep ( 3000L ) ;
} catch (InterruptedException e) {
e . printStackTrace () ;
}
System . out . println ( “main
thread work done.” ) ;
} public static class SubThread extends Thread{
***@Override
public void run ()
{
working () ;
} private void working ()
{
System . out . println ( “sub
thread start working.” ) ;
busy () ;
System . out . println ( “sub
thread stop working.” ) ;
} private void busy ()
{
try {
sleep ( 5000L ) ;
} catch (InterruptedException e) {
e . printStackTrace () ;
}
}
}
}这 里, ThreadPoolExecutor 是实现了 ExecutorService的方法, sumbit的过程就是把一个Runnable接口对象包装成一个 Callable接口对象, 然后放到 workQueue里等待调度执行. 当然, 执行的启动也是调用了thread的start来做到的, 只不过这里被包装掉了. 另外, 这里的thread是会
java线程池主线程等待子线程执行完成 来自淘豆网m.daumloan.com转载请标明出处.