转载原文处:http://blog.csdn.net/u011270461/article/details/14003951
http://www.cnblogs.com/jsunday/p/3782874.html
http://www.tuicool.com/articles/ZvAFny
因为最近对于线程方面的知识想进行了解,所以查阅了下这方面的知识进行整合。。。。有兴趣的可以进上面原文的地址去看看
1. Demo1 - thread.join()
output: 2. Demo2 - countDownLatch.await()
output: 3.主线程等待线程池执行完再执行
output:
- 0----0
- 1----0
- 0----1
- 1----1
- Thread1 End.
- 2----0
- Thread0 End.
- 2----1
- Thread2 End.
- RunTime:4019
方法4:
1 让主线程等待,或着睡眠几分钟。用Thread.sleep()或者TimeUnit.SECONDS.sleep(5);如下:
package andy.thread.traditional.test;
import java.util.concurrent.TimeUnit;
/**
* @author Zhang,Tianyou
* @version 2014年11月21日 下午11:15:27
*/
public class ThreadSubMain1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
// 模拟子线程任务
} catch (InterruptedException e) {
}
System.out.println("子线程" + Thread.currentThread() + "执行完毕");
}
}).start();
}
try {
// 等待全部子线程执行完毕
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("主线执行。");
}
}
效果如下:
子线程Thread[Thread-1,5,main]执行完毕
子线程Thread[Thread-3,5,main]执行完毕
子线程Thread[Thread-5,5,main]执行完毕
子线程Thread[Thread-7,5,main]执行完毕
子线程Thread[Thread-9,5,main]执行完毕
子线程Thread[Thread-0,5,main]执行完毕
子线程Thread[Thread-2,5,main]执行完毕
子线程Thread[Thread-4,5,main]执行完毕
子线程Thread[Thread-6,5,main]执行完毕
子线程Thread[Thread-8,5,main]执行完毕
主线执行。
此方主线程只是睡了5秒,但是不能保证全部的子线程执行完成,所以这儿的5秒只是一个估值。
方法5:
FutureDemo
使用并发包下面的Future模式.
Future是一个任务执行的结果, 他是一个将来时, 即一个任务执行, 立即异步返回一个Future对象, 等到任务结束的时候, 会把值返回给这个future对象里面. 我们可以使用 ExecutorService接口来提交一个线程.(注意:Future.get()为一个阻塞方法)
示例:
package com.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureDemo {
//创建一个容量为1的线程池
static ExecutorService executorService = Executors.newFixedThreadPool(1);
public static void main(String[] args) throws Exception {
//创建线程并提交线程,同时获取一个future对象
Thread subThread = new Thread(new SubThread());
Future future = executorService.submit(subThread);
//主线程处理其他工作,让子线程异步去执行
mainWork();
//阻塞,等待子线程结束
future.get();
System.out.println("Now all thread done!");
//关闭线程池
executorService.shutdown();
}
//主线程工作
private static void mainWork(){
System.out.println("Main thread start work!");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main Thread work done!");
}
/**
* 子线程类
* @author fuhg
*/
private static class SubThread implements Runnable{
public void run() {
// TODO Auto-generated method stub
System.out.println("Sub thread is starting!");
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Sub thread is stopping!");
}
}
}