先给大家一个简单的需求,A B C D四个线程,要求按照顺序依次输出A B C D,
楼主第一时间想到了线程相关的join,给其中A的代码,其他相似
接下来对线程代码进行测试
Thread a = new Thread(){ @Override public void run() { try { Thread.sleep((long)(Math.random()*10000)); } catch (InterruptedException e) { e.PRintStackTrace(); } System.out.println("A"); }};a.start();//a.join();b.start();//b.join();c.start();//c.join();d.start();//d.join();测试结果跟预期想的一样,因为线程的执行顺序不确定,导致结果并不是想要的。因此打算加join方法到对应的线程对象上。分析join源码发现
public final void join() throws InterruptedException { join(0);}public final synchronized void join(long millis)throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); }join方法 synchronized修饰,即同步的是对象,那创建的4个线程应该是无法做到同步等待的, 核心代码就是while(isAlive()){wait(0)} 这个方法,
/** * Tests if this thread is alive. A thread is alive if it has * been started and has not yet died. * * @return <code>true</code> if this thread is alive; * <code>false</code> otherwise. */public final native boolean isAlive();线程源码中对isAlive方法有详细说明,while(isAlive()){wait(0)}的作用就是 当某个线程没有进入死亡状态的话,这个线程会一直执行wait(0) 这个方法直到线程挂掉。
在使用join方法一定要注意join的逻辑,保证其线程没有死亡的状态下进行join操作!!!
感兴趣的同学可以用Lock锁来实现类似功能
新闻热点
疑难解答