/
有三个线程T1 T2 T3,如何保证他们按顺序执行-转载
在T2的run中,调用t1.join,让t1执行完成后再让T2执行
在T2的run中,调用t2.join,让t2执行完成后再让T3执行
/
方法一:
public class Test {
private int count=2;
public static void main(String[] args) {
try {
new Test().preserveOrderViaJoin();
}catch (Exception e){
System.out.println("error!");
}
}
private void preserveOrderViaJoin() throws InterruptedException {
Thread tmp;
System.out.println("start!");
for (int i=0;i<count;i++){
tmp=new Thread(new Runnable() {
public void run() {
System.out.println("Thread.currentThread().getName():"+Thread.currentThread().getName());
}
},"Thread"+i);
tmp.start();
tmp.join();
}
System.out.println("end!");
}
}
方法二:
public void testCountDownLatch(){
final CountDownLatch countDownLatch = new CountDownLatch(0);
final CountDownLatch countDownLatch1 = new CountDownLatch(1);
final CountDownLatch countDownLatch2 = new CountDownLatch(1);
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"start");
System.out.println(Thread.currentThread().getName()+"end");
countDownLatch1.countDown();
} catch (Exception e){
System.out.println(Thread.currentThread().getName()+"exception!");
}
}
},"Thread-1");
Thread thread2 = new Thread(new Runnable() {
public void run() {
try {
countDownLatch1.await();
System.out.println(Thread.currentThread().getName()+"start");
System.out.println(Thread.currentThread().getName()+"end");
countDownLatch2.countDown();
} catch (Exception e){
System.out.println(Thread.currentThread().getName()+"exception!");
}
}
},"Thread-2");
Thread thread3 = new Thread(new Runnable() {
public void run() {
try {
countDownLatch2.await();
System.out.println(Thread.currentThread().getName()+"start");
System.out.println(Thread.currentThread().getName()+"end");
} catch (Exception e){
System.out.println(Thread.currentThread().getName()+"exception!");
}
}
},"Thread-3");
thread1.start();
thread2.start();
thread3.start();
}
根据网络上相应内容做出的整合