使用wait(),notify()方法:
public class ControlOrder {
static Object lock=new Object();
static boolean ist2Runned ;
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
synchronized (lock){
while (!ist2Runned){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("1");
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock){
System.out.println("2");
ist2Runned=true;
lock.notifyAll();
}
}
};
t1.start();
t2.start();
}
}
这样,线程运行的顺序永远是先t2,后t1。