//情况1 MainThread 在 NewThread.Join() 被调用后被阻塞,直到 NewThread 执行完毕才继续执行。 //情况2 如果join方法内有时间参数,经过试验可以得出,如果join(2000)方法里面加入了时间,比如2000,而对应的线程 //所要的时间是sleep(4000)4000毫秒,那么只是打断了2000毫秒后,join后面的代码会自动执行下去 public class ThreadJoinExample { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable(), "t1"); Thread t2 = new Thread(new MyRunnable(), "t2"); Thread t3 = new Thread(new MyRunnable(), "t3"); t1.start(); try{ System.out.println(Thread.currentThread().getName()+System.currentTimeMillis()); t1.join(2000); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"t1是否在启动中" + t1.isAlive() +System.currentTimeMillis()); System.out.println(Thread.currentThread().getName() +"t2是否在启动中" + t2.isAlive() +System.currentTimeMillis()); t2.start(); try{ t2.join(2000); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "t2是否在启动中" + t2.isAlive() +System.currentTimeMillis()); System.out.println("t1是否在启动中" + t1.isAlive()); t3.start(); try{ System.out.println(Thread.currentThread().getName() + "t1是否在启动中" + t1.isAlive() +System.currentTimeMillis()); System.out.println(Thread.currentThread().getName() + "t2是否在启动中" + t2.isAlive() +System.currentTimeMillis()); t1.join(); t2.join(); t3.join(); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("All threads are dead, exiting main thread"); } } class MyRunnable implements Runnable{ public void run() { System.out.println("thread start :::" + Thread.currentThread().getName()); try{ Thread.sleep(4000); } catch (InterruptedException e){ e.printStackTrace(); } System.out.println("Thread end :::" + Thread.currentThread().getName()); } }
java多线程里面的join()方法
猜你喜欢
转载自zhizhi555555.iteye.com/blog/2216391
今日推荐
周排行