java中執行緒執行順序控制
阿新 • • 發佈:2019-01-01
一:join()方法.
thread.Join把指定的執行緒加入到當前執行緒,可以將兩個交替執行的執行緒合併為順序執行的執行緒。比如線上程B中呼叫了執行緒A的Join()方法,直到執行緒A執行完畢後,才會繼續執行執行緒B。
public
class
JoinTest2 {
//
1.現在有T1、T2、T3三個執行緒,你怎樣保證T2在T1執行完後執行,T3在T2執行完後執行
public
static
void
main(String[] args) {
final
Thread t1 =
new
Thread(
new
Runnable() {
@Override
public
void
run() {
System.out.println(
"t1"
);
}
});
final
Thread t2 =
new
Thread(
new
Runnable() {
@Override
public
void
run() {
try
{
//
引用t1執行緒,等待t1執行緒執行完
t1.join();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"t2"
);
}
});
Thread
t3 =
new
Thread(
new
Runnable() {
@Override
public
void
run() {
try
{
//
引用t2執行緒,等待t2執行緒執行完
t2.join();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"t3"
);
}
});
t3.start();
//這裡三個執行緒的啟動順序可以任意,大家可以試下!
t2.start();
t1.start();
}
}
二:synchronized
public class TestSync implements Runnable { Timer timer = new Timer(); public static void main(String[] args) { TestSync testSync = new TestSync(); Thread t1 = new Thread(testSync); Thread t2 = new Thread(testSync); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); } public void run() { timer.add(Thread.currentThread().getName()); } } class Timer { private static int num = 0; //public void add(String name) { public synchronized void add(String name) {//執行這個方法的過程中當前物件被鎖定 //synchronized (this) {//鎖定當前物件 num++; try { Thread.sleep(1); } catch (InterruptedException e) { } System.out.println(name + "你是第" + num + "個使用Timer的執行緒"); //} } }