Java 线程学习 (三)

tech2025-09-20  36

join 方法详解

static int r = 0; public static void main(String[] args) throws InterruptedException { test(); } private static void test() throws InterruptedException { System.out.println("开始"); Thread t1 = new Thread( () -> { try { System.out.println("线程开始:"); TimeUnit.SECONDS.sleep(1); System.out.println("线程结束"); r = 10; } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start(); t1.join(); System.out.println("结束 r的值:" + r); }

以调用方角度来讲,如果

需要等待结果返回,才能继续运行就是同步不需要等待结果返回,就能继续运行就是异步

有时效的 join 等待

static int r1 = 0; static int r2 = 0; public static void main(String[] args) throws InterruptedException { test3(); } private static void test3() throws InterruptedException { Thread t1 = new Thread( () -> { try { TimeUnit.SECONDS.sleep(1); r1 = 10; } catch (InterruptedException e) { e.printStackTrace(); } }); long start = System.currentTimeMillis(); t1.start(); t1.join(1500); long end = System.currentTimeMillis(); System.out.printf("r1: %d r2: %d cost: %d", r1, r2, end - start); }

输出

r1: 10 r2: 0 cost: 1004

interrupt 方法详解

打断 sleep , wait , join 的线程

这几个方法都会让线程进入阻塞状态

打断 sleep 的线程, 会清空打断状态 , 以 sleep 为例

public static void main(String[] args) throws InterruptedException { test1(); } private static void test1() throws InterruptedException { Thread t1 = new Thread( () -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }, "t1"); t1.start(); TimeUnit.SECONDS.sleep(1); t1.interrupt(); System.out.println("打断状态: " + t1.isInterrupted()); } 打断状态: false

打断正常运行的线程

打断正常运行的线程,不会清空打断状态

private static void test2() throws InterruptedException { Thread t2 = new Thread(() -> { while(true) { Thread current = Thread.currentThread(); boolean interrupted = current.isInterrupted(); if(interrupted) { System.out.println("打断状态: ", interrupted); break; } } }, "t2"); t2.start(); TimeUnit.SECONDS.sleep(1); t2.interrupt(); }

输出

打断状态: true
最新回复(0)