赞
踩
第一种:
用Thread.join() 方法 确定该线程执行完毕
第二种
线程池 newSingleThreadExecutor 这个线程处理完一个任务后接着处理下一个任务
具体代码:
第一种:
package com.cun;
public class JoinTest {
public static void main(String[] args) {
final Thread join1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join1");
}
}, "T1");
final Thread join2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join2");
try {
join1.join();//确定join1执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "T2");
final Thread join3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join3");
try {
join2.join();//确定join2执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "T3");
join1.start();
join2.start();
join3.start();
}
}
第二种:
package com.cun;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class JoinTest1 {
public static void main(String[] args) {
final Thread join1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join1");
}
}, "T1");
final Thread join2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join2");
}
}, "T2");
final Thread join3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join3");
}
}, "T3");
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(join1);
executor.submit(join2);
executor.submit(join3);
executor.shutdown();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。