java多线程-合并
线程合并的意义就是几个并行的线程合并为一个单线程执行,应用于一个线程必须等待另个线程执行完毕后执行
例题:现有一个主线程,T1,T2怎么让T2在T1之后执行,主线程在T2之后执行package cn.thread;
public class ThreadJoin {
public static void main(String[] args) {
ThreadJoin join = new ThreadJoin();
Thread t1 = join.new MyThread1();
Thread t2 = new Thread(join.new MyRunnable());
t1.start();
t2.start();
for (int i = 0; i < 5; i++) {
if (i==0)
try {
// t1线程合并到主线程中,主线程停止执行过程,转而执行t1线程,直到t1执行完毕后继续。
t1.join();
// t2线程合并到主线程中,主线程停止执行过程,执行完t1线程,执行t2线程
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程第" + i + "次执行!");
}
}
class MyThread1 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程1第" + i + "次执行!");
}
}
}
class MyRunnable implements Runnable{
public void run() {
for(int i = 0;i < 5;i++){
System.out.println("线程2第"+i+"次执行! ");
}
}
}
}
原文:http://blog.csdn.net/u013777676/article/details/46007847