1.单线程开始并执行完毕
当线程开始后,需要用到join的方法
不废话直接贴代码
public static void main(String args[]) {
long begin = System.currentTimeMillis();
System.out.println(begin);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("111");
}
});
try {
thread.start();
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-begin);
System.out.println("执行完毕");
}
运行结果:
1502091332017
111
1002
执行完毕
现在我们来看一下join这个方法
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
翻译为中文大意就是,等待线程执行完毕!
2.等待线程池执行完毕
等待线程池执行完毕我们需要用到
CountDownLatch这个类
且看代码:
public static void main(String args[]) throws InterruptedException {
final CountDownLatch count = new CountDownLatch(3);
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
try {
long begin = System.currentTimeMillis();
System.out.println(begin);
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000L);
count.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("111");
}
});
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000L);
count.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("222");
}
});
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000L);
count.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("333");
}
});
count.await();
long end = System.currentTimeMillis();
System.out.println(end-begin);
System.out.println("执行完毕");
} finally {
fixedThreadPool.shutdown();
}
}
最后一定要记得线程池关闭, 要不会出大问题的
运行结果:
1502091739441
111
222
333
3002
执行完毕