一、判断线程是否启动
isAlive()方法来确定一个线程是否启动
主线程(main)有可能先执行完,此时分线程不受影响
二、线程强制运行
join()方法可以让一个线程强制运行,在此期间,其他线程无法运行,必须等此线程执行完毕才能继续运行
public class Test { public static void main(String[] args) { MyThread mt1 = new MyThread(); Thread thread = new Thread(mt1,"t1"); System.out.println(thread.isAlive() + "+++++++++++++++++++++++++");//false thread.start(); System.out.println(thread.isAlive() + "+++++++++++++++++++++++++");//true for(int i = 1; i <= 10; i++) { if (i == 5) { try { thread.join();//强制运行,知道结束,其他线程才能运行 }catch(InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "运行" + i); } System.out.println(thread.isAlive() + "+++++++++++++++++++++++++"); } } class MyThread implements Runnable { public void run() { for(int i = 1; i <= 10; i++) { System.out.println(Thread.currentThread().getName() + "运行" + i); } } }
时间: 2024-10-11 07:40:12