1. 程式人生 > >如何保證線程的執行順序

如何保證線程的執行順序

new t 使用 ace == sys static ews current pre

示例代碼

static Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("Thread1");
}
});
static Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("Thread2");
}
});
static Thread t3 = new Thread(new Runnable() {
public void run() {
System.out.println("Thread3");
}
});
1.使用join


public static void main(String[] args) throws InterruptedException {
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
}
join源碼:
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;

if (millis < 0) {

throw new IllegalArgumentException("timeout value is negative");
}

if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
join讓主線程等待,至子線程執行結束
2.使用ExecutorService


static ExecutorService es = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
es.submit(t1);
es.submit(t2);
es.submit(t3);
es.shutdown();
}
ExecutorService 提供了4種線程池,分別是:
newCachedThreadPool;緩存線程池,可靈活回收、新建
newFixedThreadPool;定長線程池,可控制最大並發數,超出在隊列中等待
newScheduledThreadPool;定長線程池,可定時、周期執行
newSingleThreadExecutor;單一線程池,按順序執行(FIFO,LIFO,優先級)

如何保證線程的執行順序