1 .用join
join 不仅可以让子线程等待执行,主线程也可以
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
test.executeTask2();
}
static Logger log = LoggerFactory.getLogger(Task1.class);
public void executeTask2() throws InterruptedException {
Object o = new Object();
Integer a = 2;
while (a > 0) {
Thread t0 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
log.info("==============================t0 started !");
Thread.sleep(5000);
log.info("==============================t0 finished !");
}
});
Thread t1 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
t0.start();
t0.join();
Thread.sleep(5000);
log.info("==============================t1 started !");
log.info("==============================t1 finished !");
}
});
t1.start();
t1.join();
a--;
System.out.println("I am main1");
}
System.out.println("I am main");
}
2 notify和wait
public void executeTask2() throws InterruptedException {
Object o = new Object();
Integer a = 2;
while (a > 0) {
Thread t0 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
log.info("==============================t0 started !");
Thread.sleep(5000);
log.info("==============================t0 finished !");
}
});
Thread t1 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
t0.start();
t0.join();
Thread.sleep(5000);
log.info("==============================t1 started !");
log.info("==============================t1 finished !");
synchronized (o){
o.notify();
}
}
});
t1.start();
synchronized (o){
o.wait();
}
a--;
System.out.println("I am main1");
}
System.out.println("I am main");
}
这两种我常用 后面的还没用过我就贴个链接吧
java 主线程等待的其中方法