在多线程并发执行中每一个线程对象都会交替执行,如果此时某个线程对象需要优先执行完成,则可以设置为强制执行,待其执行完毕后其他线程在继续执行,Thread类定义的线程强制执行方法如下。
线程强制执行:public void join() throws InterruptedException
范例:线程强制执行
public class ThreadDemo317 {
public static void main(String[] args) throws InterruptedException {
Thread mainThread=Thread.currentThread(); //获得主线程
Thread thread=new Thread(()->{
for (int i = 0; i < 100; i++) {
if(i==3) { //强制执行条件
try {
mainThread.join(); //强制执行线程任务
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(100); //延缓执行
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行、x="+i);
}
},"玩耍的线程") ;
thread.start();
for (int i = 0; i < 100; i++) { //主线程
Thread.sleep(100);
System.out.println("【霸道的main线程】number="+i);
}
}
}
本程序启动了两个线程:main线程和子线程,在不满足强制执行条件时,两个线程会交替执行,而当满足了强制执行条件(i==3)时会在主线程执行完毕后在继续执行子线程的代码。