public class Test { public static void main(String[] args) { Thread t = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("-------"); }); t.start(); // 调用了start方法且线程没死亡返回true while (t.isAlive()) { } System.out.println("main"); }}
public class Test { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("-------"); }); t.start(); t.join(); System.out.println("main"); }}
public class Test { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); Thread t = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("-------"); countDownLatch.countDown(); }); t.start(); countDownLatch.await(); System.out.println("main"); }}
public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<Integer> myCallable = new MyCallable(); FutureTask<Integer> futureTask = new FutureTask<>(myCallable); Thread thread = new Thread(futureTask); thread.start(); futureTask.get(); System.out.println("main"); }}class MyCallable implements Callable<Integer> { @Override public Integer call() throws InterruptedException { Thread.sleep(5000); System.out.println("-----------"); return 1; }}
public class Test { public static void main(String[] args) throws InterruptedException { BlockingQueue queue = new ArrayBlockingQueue(1); Thread t = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("-------"); try { queue.put("1"); } catch (InterruptedException e) { e.printStackTrace(); } }); t.start(); queue.take(); System.out.println("main"); }}
public class Test { public static void main(String[] args) throws InterruptedException, BrokenBarrierException { CyclicBarrier barrier = new CyclicBarrier(2); Thread t = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("-------"); try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }); t.start(); barrier.await(); System.out.println("main"); }}
public class Test { public static void main(String[] args) throws InterruptedException, BrokenBarrierException { Thread mainThread = Thread.currentThread(); Thread t = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("-------"); LockSupport.unpark(mainThread); }); t.start(); LockSupport.park(); System.out.println("main"); }}