Thread.join()
假设此时有主线程main和子线程thread1,在main中启动thread1。如果thread1需要进行大量的计算工作,那么有可能main会先于thread1结束。当main需要用到thread1的计算结果时,我们就可以在调用了thread.start()
方法后,再调用thread1.join()
方法,此时main
就会等thread1
执行完再执行。并且线程thread1
被打断后会抛出interruptedException
异常。
//join方法有三种重载形式
public final synchronized void join(long millis, int nanos) throws InterruptedException
public final synchronized void join(long millis) throws InterruptedException
public final void join() throws InterruptedException
使用方法如下所示
//主线程的代码
thread1.start();
thread1.join();
//主线程的后续代码
Thread.sleep()
Thread.sleep()
方法是Thread类中的一个静态方法,作用是使当前线程休眠指定的时间,如果在休眠期间被打断,会抛出InterruptedException
异常。
注意:Thread.sleep()方法是在哪个个线程中被调用,哪个线程就进入休眠,就算是在main
线程中以thread1.sleep()
的形式调用,也会是main
线程进入休眠,而不是thread1
线程
//sleep()方法有两种重载形式
//休眠指定的毫秒数
public static native void sleep(long millis) throws InterruptedException
//休眠指定的毫秒数加纳秒数
public static void sleep(long millis, int nanos)throws InterruptedException {}
Object.wait()
wait()
方法是Object类中的方法,当我们在线程中调用某个对象(假设为obj1
)的wait()
方法时,会让该线程进入阻塞状态,进入到obj1
的等待池中,并且会释放该线程所持有的锁,直到有其他线程调用obj1.notify()或obj1.notifyAll()
方法,阻塞状态中的线程如果被中断,会抛出InterruptedException
异常。这时等待中的线程会被唤醒,进入到obj1
的锁定池中,与锁定池中的其他线程竞争锁,如果成功获得锁,就会进入到就绪状态(Runnable状态)。
//wait()方法有三种重载形式
public final native void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException
public final void wait() throws InterruptedException
CyclicBarrier.await()
有些情况下,我们希望多个线程可以保持一定的同步,比如当某个线程运行到一个程序的某个节点时,阻塞在那个位置,等待其他线程的到达。当所有线程全部到达之后,再放行,让那些线程继续运行。java中的CyclicBarrier
类位java.util.concurrent
包下,我们可以用它设置一个运行节点,当某个线程运行到了某个位置时,就可以调用CyclicBarrier实例的await()
方法,让其阻塞等待。阻塞中的线程被打断后会抛出InterruptedException
异常。
//await()方法有两种重载形式
public int await() throws InterruptedException, BrokenBarrierException{}
public int await(long timeout, TimeUnit unit) throws InterruptedException,BrokenBarrierException,TimeoutException{}
Thread.suspend()
Thread类的suspend()
方法用于暂停一个线程,并且不会释放该线程持有的锁,是一个被废弃的方法,不会抛出InterruptedException
异常,经由suspend()
方法被暂停的线程可以用resume()
方法恢复。
//@Deprecated注解标志该方法不推荐使用
@Deprecated
public final void suspend() {
checkAccess();
suspend0();
}