3.Java 线程 本章内容
3.1 创建和运行线程 方法一,直接使用 Thread 1 2 3 4 5 6 7 8 Thread t = new Thread () { public void run () { } }; t.start();
例如:
1 2 3 4 5 6 7 8 9 Thread t1 = new Thread ("t1" ) { @Override public void run () { log.debug("hello" ); } }; t1.start();
输出:
1 19:19:00 [t1] c.ThreadStarter - hello
方法二,使用 Runnable 配合 Thread 把【线程】和【任务】(要执行的代码)分开
Thread 代表线程
Runnable 可运行的任务(线程要执行的代码)
1 2 3 4 5 6 7 8 9 Runnable runnable = new Runnable () { public void run () { } }; Thread t = new Thread ( runnable );t.start();
例如:
1 2 3 4 5 6 7 8 9 10 Runnable task2 = new Runnable () { @Override public void run () { log.debug("hello" ); } }; Thread t2 = new Thread (task2, "t2" );t2.start();
输出:
1 9:19:00 [t2] c.ThreadStarter - hello
Java 8 以后可以使用 lambda 精简代码
1 2 3 4 5 Runnable task2 = () -> log.debug("hello" );Thread t2 = new Thread (task2, "t2" );t2.start();
Thread 与 Runnable 的关系 分析 Thread 的源码,理清它与 Runnable 的关系
1 2 3 4 public interface Runnable { public abstract void run () ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Thread implements Runnable { private Runnable target; public Thread (Runnable target) { init(null , target, "Thread-" + nextThreadNum(), 0 ); } private void init (ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) { this .target = target; } @Override public void run () { if (target != null ) { target.run(); } }
小结
方法1 是把线程和任务合并在了一起,方法2 是把线程和任务分开了
用 Runnable 更容易与线程池等高级API 配合
用 Runnable 让任务类脱离了 Thread 继承体系,更灵活
方法三,FutureTask 配合 Thread FutureTask 能够接收 Callable 类型的参数,用来处理有返回结果的情况
1 2 3 4 5 6 7 8 9 10 FutureTask<Integer> task3 = new FutureTask <>(() -> { log.debug("hello" ); return 100 ; }); new Thread (task3, "t3" ).start();Integer result = task3.get();log.debug("结果是:{}" , result);
输出
1 2 19:22:27 [t3] c.ThreadStarter - hello 19:22:27 [main] c.ThreadStarter - 结果是:100
源码分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 public class FutureTask <V> implements RunnableFuture <V> { private Callable<V> callable; private Object outcome; public FutureTask (Callable<V> callable) { if (callable == null ) throw new NullPointerException (); this .callable = callable; this .state = NEW; } public void run () { try { Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true ; } catch (Throwable ex) { result = null ; ran = false ; setException(ex); } if (ran) set(result); } } } protected void set (V v) { if (UNSAFE.compareAndSwapInt(this , stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this , stateOffset, NORMAL); finishCompletion(); } } public V get () throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false , 0L ); return report(s); } private V report (int s) throws ExecutionException { Object x = outcome; if (s == NORMAL) return (V)x; if (s >= CANCELLED) throw new CancellationException (); throw new ExecutionException ((Throwable)x); } }
RunnableFuture
继承 Future 可以返回携带结果
1 2 3 4 5 public interface RunnableFuture <V> extends Runnable , Future<V> { void run () ; }
1 2 3 4 5 6 7 8 9 10 11 @FunctionalInterface public interface Callable <V> { V call () throws Exception; }
说明:
FutureTask内置了一个Callable对象,初始化方法将指定的Callable赋给这个对象。
FutureTask实现了Runnable接口,并重写了Run方法,在Run方法中调用了Callable中的call方法,并将返回值赋值给outcome变量
get方法就是取出outcome的值。
3.2 观察多个线程同时运行 主要是理解
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Slf4j(topic = "c.TestMultiThread") public class TestMultiThread { public static void main (String[] args) { new Thread (() -> { while (true ) { log.debug("running" ); } },"t1" ).start(); new Thread (() -> { while (true ) { log.debug("running" ); } },"t2" ).start(); } }
运行结果:
1 2 3 4 5 6 7 8 9 10 23:45:26.254 c.TestMultiThread [t2] - running 23:45:26.254 c.TestMultiThread [t2] - running 23:45:26.254 c.TestMultiThread [t2] - running 23:45:26.254 c.TestMultiThread [t2] - running 23:45:26.254 c.TestMultiThread [t1] - running 23:45:26.254 c.TestMultiThread [t1] - running 23:45:26.254 c.TestMultiThread [t1] - running 23:45:26.254 c.TestMultiThread [t1] - running 23:45:26.254 c.TestMultiThread [t1] - running 23:45:26.254 c.TestMultiThread [t1] - running
3.3 查看进程线程的方法 windows
任务管理器可以查看进程和线程数,也可以用来杀死进程
tasklist 查看进程
tasklist | findstr (查找关键字)
taskkill 杀死进程
taskkill /F(彻底杀死)/PID(进程PID)
Linux
ps -fe 查看所有进程
ps -fT -p 查看某个进程(PID)的所有线程
kill 杀死进程 top 按大写 H 切换是否显示线程
top -H -p 查看某个进程(PID)的所有线程
Java
jps 命令查看所有 Java 进程
jstack 查看某个 Java 进程(PID)的所有线程状态
jconsole 来查看某个 Java 进程中线程的运行情况(图形界面)
jconsole 远程监控配置
1 2 3 4 5 6 7 java -Djava.rmi.server.hostname=`ip地址` -Dcom.sun.management.jmxremote - Dcom.sun.management.jmxremote.port=`连接端口` -Dcom.sun.management.jmxremote.ssl=是否安全连接 - Dcom.sun.management.jmxremote.authenticate=是否认证 java类 java -Djava.rmi.server.hostname=`localhost` -Dcom.sun.management.jmxremote - Dcom.sun.management.jmxremote.port=`12345` -Dcom.sun.management.jmxremote.ssl=false - Dcom.sun.management.jmxremote.authenticate=false Test2
关闭防火墙,允许端口
修改 /etc/hosts 文件将 127.0.0.1 映射至主机名 如果要认证访问,还需要做如下步骤
复制 jmxremote.password 文件
修改 jmxremote.password 和 jmxremote.access 文件的权限为 600 即文件所有者可读写
连接时填入 controlRole(用户名),R&D(密码)
3.4 原理之线程运行 栈与栈帧 Java Virtual Machine Stacks (Java 虚拟机栈) 我们都知道 JVM 中由堆、栈、方法区所组成,其中栈内存是给谁用的呢?其实就是线程,每个线程启动后,虚拟 机就会为其分配一块栈内存。
每个栈由多个栈帧(Frame)组成,对应着每次方法调用时所占用的内存
每个线程只能有一个活动栈帧,对应着当前正在执行的那个方法
多线程直接的栈帧互不影响
图解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class TestFrames { public static void main (String[] args) { method1(10 ); } private static void method1 (int x) { int y = x + 1 ; Object m = method2(); System.out.println(m); } private static Object method2 () { Object n = new Object (); return n; } }
多线程 :
右击断点选择线程
多线程直接的栈帧不影响
main线程
t2线程
线程上下文切换(Thread Context Switch) 因为以下一些原因导致 cpu 不再执行当前的线程,转而执行另一个线程的代码
线程的 cpu 时间片用完
垃圾回收
有更高优先级的线程需要运行
线程自己调用了 sleep、yield、wait、join、park、synchronized、lock 等方法 当 Context Switch 发生时,需要由操作系统保存当前线程的状态,并恢复另一个线程的状态,Java 中对应的概念 就是程序计数器(Program Counter Register),它的作用是记住下一条 jvm 指令的执行地址,是线程私有的
状态包括程序计数器、虚拟机栈中每个栈帧的信息,如局部变量、操作数栈、返回地址等
Context Switch 频繁发生会影响性能
3.5常见方法
方法
功能
说明
public void start()
启动一个新线程;Java虚拟机调用此线程的run方法
start 方法只是让线程进入就绪,里面代码不一定立刻 运行(CPU 的时间片还没分给它)。每个线程对象的 start方法只能调用一次,如果调用了多次会出现 IllegalThreadStateException
public void run()
线程启动后调用该方法
如果在构造 Thread 对象时传递了 Runnable 参数,则 线程启动后会调用 Runnable 中的 run 方法,否则默 认不执行任何操作。但可以创建 Thread 的子类对象, 来覆盖默认行为
join()
等待线程运行结束
join(long n)
等待线程运行结 束,最多等待 n 毫秒
public void setName(String name)
给当前线程取名字
public void getName()
获取当前线程的名字。线程存在默认名称:子线程是Thread-索引,主线程是main
public static Thread currentThread()
获取当前线程对象,代码在哪个线程中执行
public static void sleep(long time)
让当前线程休眠多少毫秒再继续执行。Thread.sleep(0) : 让操作系统立刻重新进行一次cpu竞争
public static native void yield()
提示线程调度器让出当前线程对CPU的使用,类似sleep,但是没有时间
主要是为了测试和调试
public final int getPriority()
返回此线程的优先级
public final void setPriority(int priority)
更改此线程的优先级,常用1 5 10
java中规定线程优先级是1~10 的整数,较大的优先级 能提高该线程被 CPU 调度的机率
public void interrupt()
中断这个线程,异常处理机制
public static boolean interrupted()
判断当前线程是否被打断,清除打断标记
public boolean isInterrupted()
判断当前线程是否被打断,不清除打断标记
public final void join()
等待这个线程结束
public final void join(long millis)
等待这个线程死亡millis毫秒,0意味着永远等待
public final native boolean isAlive()
线程是否存活(还没有运行完毕)
public final void setDaemon(boolean on)
将此线程标记为守护线程或用户线程
public long getId()
获取线程长整型 的 id
id 唯一
public state getState()
获取线程状态
Java 中线程状态是用 6 个 enum 表示,分别为: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
public boolean isInterrupted()
判断是否被打 断
不会清除 打断标记
3.6 start 与 run 调用 run
1 2 3 4 5 6 7 8 9 10 11 public static void main (String[] args) { Thread t1 = new Thread ("t1" ) { @Override public void run () { log.debug(Thread.currentThread().getName()); FileReader.read(Constants.MP4_FULL_PATH); } }; t1.run(); log.debug("do other things ..." ); }
输出
1 2 3 4 19:39:14 [main] c.TestStart - main 19:39:14 [main] c.FileReader - read [1.mp4] start ... 19:39:18 [main] c.FileReader - read [1.mp4] end ... cost: 4227 ms 19:39:18 [main] c.TestStart - do other things ...
程序仍在 main 线程运行, FileReader.read() 方法调用还是同步的
调用start 将上述代码的 t1.run() 改为
输出
1 2 3 4 19:41:30 [main] c.TestStart - do other things ... 19:41:30 [t1] c.TestStart - t1 19:41:30 [t1] c.FileReader - read [1.mp4] start ... 19:41:35 [t1] c.FileReader - read [1.mp4] end ... cost: 4542 ms
程序在 t1 线程运行, FileReader.read() 方法调用是异步的
小结
直接调用 run 是在主线程中执行了 run,没有启动新的线程
使用 start 是启动新的线程,通过新的线程间接执行 run 中的代码
1 2 3 4 5 6 7 8 9 10 11 public static void main (String[] args) { Thread t1 = new Thread ("t1" ) { @Override public void run () { log.debug("running..." ); } }; System.out.println(t1.getState()); t1.start(); System.out.println(t1.getState()); }
可以看见,start方法创建了一个新线程,将线程从就绪状态切换为Runnable 1 2 3 NEW RUNNABLE 03:45:12.255 c.Test5 [t1] - running...
3.7 sleep 与 yield sleep
调用 sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
其它线程可以使用 interrupt 方法打断正在睡眠的线程,这时 sleep 方法会抛出 InterruptedException
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public static void main (String[] args) throws InterruptedException { Thread t1 = new Thread ("t1" ) { @Override public void run () { log.debug("enter sleep..." ); try { Thread.sleep(2000 ); } catch (InterruptedException e) { log.debug("wake up..." ); e.printStackTrace(); } } }; t1.start(); Thread.sleep(1000 ); log.debug("interrupt..." ); t1.interrupt(); }
输出结果: 1 2 3 4 5 6 03:47:18.141 c.Test7 [t1] - enter sleep ... 03:47:19.132 c.Test7 [main] - interrupt... 03:47:19.132 c.Test7 [t1] - wake up... java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep (Native Method) at cn.itcast.test.Test7$1 .run(Test7.java:14)
睡眠结束后的线程未必会立刻得到执行
建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性 。其底层还是sleep方法。
1 2 3 4 5 6 7 8 9 10 @Slf4j(topic = "c.Test8") public class Test8 { public static void main (String[] args) throws InterruptedException { log.debug("enter" ); TimeUnit.SECONDS.sleep(1 ); log.debug("end" ); } }
在循环访问锁的过程中,可以加入sleep让线程阻塞时间,防止大量占用cpu资源。
yield
调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程
具体的实现依赖于操作系统的任务调度器
线程优先级
线程优先级会提示(hint)调度器优先调度该线程,但它仅仅是一个提示,调度器可以忽略它
如果 cpu 比较忙,那么优先级高的线程会获得更多的时间片,但 cpu 闲时,优先级几乎没作用
测试优先级和yield 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @Slf4j(topic = "c.TestYield") public class TestYield { public static void main (String[] args) { Runnable task1 = () -> { int count = 0 ; for (;;) { System.out.println("---->1 " + count++); } Runnable task2 = () -> { int count = 0 ; for (;;) { System.out.println(" ---->2 " + count++); } }; Thread t1 = new Thread (task1, "t1" ); Thread t2 = new Thread (task2, "t2" ); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); } }
测试结果:
1 2 3 4 5 6 ---->1 283500 ---->2 374389 ---->1 119199 ---->2 101074
可以看出,线程优先级和yield会对线程获取cpu时间片产生一定影响,但不会影响太大。
应用之限制(案例1) sleep 实现 在没有利用 cpu 来计算时,不要让 while(true) 空转浪费 cpu,这时可以使用 yield 或 sleep 来让出 cpu 的使用权 给其他程序
1 2 3 4 5 6 7 while (true ) { try { Thread.sleep(50 ); } catch (InterruptedException e) { e.printStackTrace(); } }
可以用 wait 或 条件变量达到类似的效果
不同的是,后两种都需要加锁,并且需要相应的唤醒操作,一般适用于要进行同步的场景
sleep 适用于无需锁同步的场景
wait 实现 1 2 3 4 5 6 7 8 9 10 synchronized (锁对象) { while (条件不满足) { try { 锁对象.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
条件变量实现 1 2 3 4 5 6 7 8 9 10 11 12 13 lock.lock(); try { while (条件不满足) { try { 条件变量.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } finally { lock.unlock(); }
3.8 join 方法详解 为什么需要 join 下面的代码执行,打印 r 是什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 static int r = 0 ;public static void main (String[] args) throws InterruptedException { test1(); } private static void test1 () throws InterruptedException { log.debug("开始" ); Thread t1 = new Thread (() -> { log.debug("开始" ); sleep(1 ); log.debug("结束" ); r = 10 ; }); t1.start(); log.debug("结果为:{}" , r); log.debug("结束" ); }
分析
因为主线程和线程 t1 是并行执行的,t1 线程需要 1 秒之后才能算出 r=10
而主线程一开始就要打印 r 的结果,所以只能打印出 r=0 解决方法
用 sleep 行不行?为什么?
用 join,加在 t1.start() 之后即可
应用之同步(案例1) 以调用方角度来讲,如果
需要等待结果返回,才能继续运行就是同步
不需要等待结果返回,就能继续运行就是异步
等待多个结果 问,下面代码 cost 大约多少秒?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 static int r1 = 0 ;static int r2 = 0 ;public static void main (String[] args) throws InterruptedException { test2(); } private static void test2 () throws InterruptedException { Thread t1 = new Thread (() -> { sleep(1 ); r1 = 10 ; }); Thread t2 = new Thread (() -> { sleep(2 ); r2 = 20 ; }); long start = System.currentTimeMillis(); t1.start(); t2.start(); t1.join(); t2.join(); long end = System.currentTimeMillis(); log.debug("r1: {} r2: {} cost: {}" , r1, r2, end - start); }
分析如下
第一个 join:等待 t1 时, t2 并没有停止, 而在运行
第二个 join:1s 后, 执行到此, t2 也运行了 1s, 因此也只需再等待 1s
整个程序运行了2s 如果颠倒两个 join 呢?
结果一样
如图右侧所示 最终都是输出
1 20:45:43.239 [main] c.TestJoin - r1: 10 r2: 20 cost: 2005
有时效的join 当线程执行时间没有超过join设定时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 static int r1 = 0 ;static int r2 = 0 ;public static void main (String[] args) throws InterruptedException { test3(); } public static void test3 () throws InterruptedException { Thread t1 = new Thread (() -> { sleep(1 ); r1 = 10 ; }); long start = System.currentTimeMillis(); t1.start(); t1.join(1500 ); long end = System.currentTimeMillis(); log.debug("r1: {} r2: {} cost: {}" , r1, r2, end - start); }
输出
1 20:48:01.320 [main] c.TestJoin - r1: 10 r2: 0 cost: 1010
当执行时间超时
t1等待2秒,再给r1赋值为10
t1.join(1500); 只等1.5s 最终r1还是0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 static int r1 = 0 ;static int r2 = 0 ;public static void main (String[] args) throws InterruptedException { test3(); } public static void test3 () throws InterruptedException { Thread t1 = new Thread (() -> { sleep(2 ); r1 = 10 ; }); long start = System.currentTimeMillis(); t1.start(); t1.join(1500 ); long end = System.currentTimeMillis(); log.debug("r1: {} r2: {} cost: {}" , r1, r2, end - start); }
输出
1 20:52:15.623 [main] c.TestJoin - r1: 0 r2: 0 cost: 1502
3.9 interrupt方法详解 Interrupt说明interrupt的本质是将线程的打断标记设为true,并调用线程的三个par ker对象(C++实现级别)unpark该线程。 基于以上本质,有如下说明:
打断线程不等于中断线程 ,有以下两种情况:
打断正在运行中的线程并不会影响线程的运行,但如果线程监测到了打断标记为true,可以自行决定后续处理。
打断阻塞中的线程会让此线程产生一个InterruptedException异常,将打断标记置为false,结束线程的运行。但如果该异常被线程捕获住,该线程依然可以自行决定后续处理(终止运行,继续运行,做一些善后工作等等)
打断 sleep,wait,join 的线程 这几个方法都会让线程进入阻塞状态 打断 sleep 的线程, 会清空打断状态,以 sleep 为例
1 2 3 4 5 6 7 8 9 private static void test1 () throws InterruptedException { Thread t1 = new Thread (()->{ sleep(1 ); }, "t1" ); t1.start(); sleep(0.5 ); t1.interrupt(); log.debug(" 打断状态: {}" , t1.isInterrupted()); }
输出
1 2 3 4 5 6 7 8 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep (Native Method) at java.lang.Thread.sleep (Thread.java:340) at java.util.concurrent.TimeUnit.sleep (TimeUnit.java:386) at cn.itcast.n2.util.Sleeper.sleep (Sleeper.java:8) at cn.itcast.n4.TestInterrupt.lambda$test1$3 (TestInterrupt.java:59) at java.lang.Thread.run(Thread.java:745) 21:18:10.374 [main] c.TestInterrupt - 打断状态: false
打断正常运行的线程 打断正常运行的线程, 不会清空打断状态
被打断后仍会继续执行
可以使用打断标记if判断后再退出线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private static void test2 () throws InterruptedException { Thread t2 = new Thread (()->{ while (true ) { Thread current = Thread.currentThread(); boolean interrupted = current.isInterrupted(); if (interrupted) { log.debug(" 打断状态: {}" , interrupted); break ; } } }, "t2" ); t2.start(); sleep(0.5 ); t2.interrupt(); }
输出
1 20:57:37.964 [t2] c.TestInterrupt - 打断状态: true
模式之两阶段终止 Two Phase Termination 在一个线程 T1 中如何“优雅”终止线程 T2?这里的【优雅】指的是给 T2 一个料理后事的机会。
错误思路
使用线程对象的 stop() 方法停止线程
stop 方法会真正杀死线程,如果这时线程锁住了共享资源,那么当它被杀死后就再也没有机会释放锁, 其它线程将永远无法获取锁
使用 System.exit(int) 方法停止线程
目的仅是停止一个线程,但这种做法会让整个程序都停止
两阶段终止模式
背景:一个监控电脑状态的程序,每隔2s记录一次
非睡眠状态下设置打断:正常
睡眠状态设置打断:抛出异常,重新设置打断标记
利用 isInterrupted interrupt 可以打断正在执行的线程,无论这个线程是在 sleep,wait,还是正常运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class TPTInterrupt { private Thread thread; public void start () { thread = new Thread (() -> { while (true ) { Thread current = Thread.currentThread(); if (current.isInterrupted()) { log.debug("料理后事" ); break ; } try { Thread.sleep(1000 ); log.debug("将结果保存" ); } catch (InterruptedException e) { current.interrupt(); } } },"监控线程" ); thread.start(); } public void stop () { thread.interrupt(); } }
调用
1 2 3 4 5 TPTInterrupt t = new TPTInterrupt ();t.start(); Thread.sleep(3500 ); log.debug("stop" ); t.stop();
结果
1 2 3 4 5 11:49:42.915 c.TwoPhaseTermination [监控线程] - 将结果保存 11:49:43.919 c.TwoPhaseTermination [监控线程] - 将结果保存 11:49:44.919 c.TwoPhaseTermination [监控线程] - 将结果保存 11:49:45.413 c.TestTwoPhaseTermination [main] - stop 11:49:45.413 c.TwoPhaseTermination [监控线程] - 料理后事
利用停止标记 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class TPTVolatile { private Thread thread; private volatile boolean stop = false ; public void start () { thread = new Thread (() -> { while (true ) { Thread current = Thread.currentThread(); if (stop) { log.debug("料理后事" ); break ; } try { Thread.sleep(1000 ); log.debug("将结果保存" ); } catch (InterruptedException e) { } } },"监控线程" ); thread.start(); } public void stop () { stop = true ; thread.interrupt(); } }
调用
1 2 3 4 5 TPTVolatile t = new TPTVolatile ();t.start(); Thread.sleep(3500 ); log.debug("stop" ); t.stop();
结果
1 2 3 4 5 11:54:52.003 c.TPTVolatile [监控线程] - 将结果保存 11:54:53.006 c.TPTVolatile [监控线程] - 将结果保存 11:54:54.007 c.TPTVolatile [监控线程] - 将结果保存 11:54:54.502 c.TestTwoPhaseTermination [main] - stop 11:54:54.502 c.TPTVolatile [监控线程] - 料理后事
打断 park 线程 打断 park 线程, 不会清空打断状态
1 2 3 4 5 6 7 8 9 10 11 private static void test3 () throws InterruptedException { Thread t1 = new Thread (() -> { log.debug("park..." ); LockSupport.park(); log.debug("unpark..." ); log.debug("打断状态:{}" , Thread.currentThread().isInterrupted()); }, "t1" ); t1.start(); sleep(0.5 ); t1.interrupt(); }
输出
1 2 3 21:11:52.795 [t1] c.TestInterrupt - park... 21:11:53.295 [t1] c.TestInterrupt - unpark... 21:11:53.295 [t1] c.TestInterrupt - 打断状态:true
如果打断标记已经是 true, 则 park 会失效
1 2 3 4 5 6 7 8 9 10 11 12 private static void test4 () { Thread t1 = new Thread (() -> { for (int i = 0 ; i < 5 ; i++) { log.debug("park..." ); LockSupport.park(); log.debug("打断状态:{}" , Thread.currentThread().isInterrupted()); } }); t1.start(); sleep(1 ); t1.interrupt(); }
输出
1 2 3 4 5 6 7 8 9 10 21:13:48.783 [Thread-0] c.TestInterrupt - park... 21:13:49.809 [Thread-0] c.TestInterrupt - 打断状态:true 21:13:49.812 [Thread-0] c.TestInterrupt - park... 21:13:49.813 [Thread-0] c.TestInterrupt - 打断状态:true 21:13:49.813 [Thread-0] c.TestInterrupt - park... 21:13:49.813 [Thread-0] c.TestInterrupt - 打断状态:true 21:13:49.813 [Thread-0] c.TestInterrupt - park... 21:13:49.813 [Thread-0] c.TestInterrupt - 打断状态:true 21:13:49.813 [Thread-0] c.TestInterrupt - park... 21:13:49.813 [Thread-0] c.TestInterrupt - 打断状态:true
提示 可以使用 Thread.interrupted() 清除打断状态,interrupted 返回打断标记后,再将打断标记置为false
3.10 不推荐的方法 还有一些不推荐使用的方法,这些方法已过时,容易破坏同步代码块,造成线程死锁
方法名
static
功能说明
stop()
停止线程运行
suspend()
挂起(暂停)线程运行
resume()
恢复线程运行
3.11 主线程与守护线程 默认情况下,Java 进程需要等待所有线程都运行结束,才会结束。有一种特殊的线程叫做守护线程,只要其它非守护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束。 例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @Slf4j(topic = "c.Test15") public class Test15 { public static void main (String[] args) throws InterruptedException { Thread t1 = new Thread (() -> { while (true ) { System.out.println("子线程在运行" ); try { Thread.sleep(1000 ); } catch (InterruptedException e) { throw new RuntimeException (e); } if (Thread.currentThread().isInterrupted()) { break ; } } log.debug("结束" ); }, "t1" ); t1.setDaemon(true ); t1.start(); Thread.sleep(1000 ); log.debug("结束" ); } }
开启 ``t1.setDaemon(true); `
1 2 3 4 5 17:13:09.498 c.Test15 [t1] - 子线程在运行 17:13:10.503 c.Test15 [t1] - 子线程在运行 17:13:10.503 c.Test15 [main] - 结束 进程已结束,退出代码为 0
若关闭 t1.setDaemon(true); 代码:
1 2 3 4 5 17:12:46.404 c.Test15 [t1] - 子线程在运行 17:12:47.409 c.Test15 [main] - 结束 17:12:47.410 c.Test15 [t1] - 子线程在运行 17:12:48.416 c.Test15 [t1] - 子线程在运行 17:12:49.417 c.Test15 [t1] - 子线程在运行
注意
垃圾回收器线程就是一种守护线程
Tomcat 中的 Acceptor 和 Poller 线程都是守护线程,所以 Tomcat 接收到 shutdown 命令后,不会等待它们处理完当前请求
3.12 五种状态 这是从 操作系统 层面来描述的
【初始状态】仅是在语言层面创建了线程对象,还未与操作系统线程关联
【可运行状态】(就绪状态)指该线程已经被创建(与操作系统线程关联),可以由 CPU 调度执行
【运行状态】指获取了 CPU 时间片运行中的状态
当 CPU 时间片用完,会从【运行状态】转换至【可运行状态】,会导致线程的上下文切换
【阻塞状态】
如果调用了阻塞 API,如 BIO 读写文件,这时该线程实际不会用到 CPU,会导致线程上下文切换,进入 【阻塞状态】
等 BIO 操作完毕,会由操作系统唤醒阻塞的线程,转换至【可运行状态】
与【可运行状态】的区别是,对【阻塞状态】的线程来说只要它们一直不唤醒,调度器就一直不会考虑 调度它们
【终止状态】表示线程已经执行完毕,生命周期已经结束,不会再转换为其它状态
3.13 六种状态 这是从 Java API 层面来描述的 根据 Thread.State 枚举,分为六种状态
NEW 线程刚被创建,但是还没有调用 start() 方法
RUNNABLE 当调用了 start() 方法之后,注意,Java API 层面的 RUNNABLE 状态涵盖了 操作系统 层面的 【可运行状态】、【运行状态】和【阻塞状态】(由于 BIO 导致的线程阻塞,在 Java 里无法区分,仍然认为 是可运行)
BLOCKED , WAITING , TIMED_WAITING 都是 Java API 层面对【阻塞状态】的细分,后面会在状态转换一节 详述
TERMINATED 当线程代码运行结束
演示六种状态 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 @Slf4j(topic = "c.TestState") public class TestState { public static void main (String[] args) throws IOException { Thread t1 = new Thread ("t1" ) { @Override public void run () { log.debug("running..." ); } }; Thread t2 = new Thread ("t2" ) { @Override public void run () { while (true ) { } } }; t2.start(); Thread t3 = new Thread ("t3" ) { @Override public void run () { log.debug("running..." ); } }; t3.start(); Thread t4 = new Thread ("t4" ) { @Override public void run () { synchronized (TestState.class) { try { Thread.sleep(1000000 ); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t4.start(); Thread t5 = new Thread ("t5" ) { @Override public void run () { try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }; t5.start(); Thread t6 = new Thread ("t6" ) { @Override public void run () { synchronized (TestState.class) { try { Thread.sleep(1000000 ); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t6.start(); try { Thread.sleep(500 ); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("t1 state {}" , t1.getState()); log.debug("t2 state {}" , t2.getState()); log.debug("t3 state {}" , t3.getState()); log.debug("t4 state {}" , t4.getState()); log.debug("t5 state {}" , t5.getState()); log.debug("t6 state {}" , t6.getState()); System.in.read(); } }
1 2 3 4 5 6 7 17:27:28.103 c.TestState [t3] - running... 17:27:28.606 c.TestState [main] - t1 state NEW 17:27:28.606 c.TestState [main] - t2 state RUNNABLE 17:27:28.606 c.TestState [main] - t3 state TERMINATED 17:27:28.606 c.TestState [main] - t4 state TIMED_WAITING 17:27:28.606 c.TestState [main] - t5 state WAITING 17:27:28.607 c.TestState [main] - t6 state BLOCKED
3.14 习题 阅读华罗庚《统筹方法》,给出烧水泡茶的多线程解决方案,提示
参考图二,用两个线程(两个人协作)模拟烧水泡茶过程
文中办法乙、丙都相当于任务串行
而图一相当于启动了 4 个线程,有点浪费
用 sleep(n) 模拟洗茶壶、洗水壶等耗费的时间
应用之统筹(烧水泡茶) 解法1:join
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Thread t1 = new Thread (() -> { log.debug("洗水壶" ); sleep(1 ); log.debug("烧开水" ); sleep(15 ); }, "老王" ); Thread t2 = new Thread (() -> { log.debug("洗茶壶" ); sleep(1 ); log.debug("洗茶杯" ); sleep(2 ); log.debug("拿茶叶" ); sleep(1 ); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("泡茶" ); }, "小王" ); t1.start(); t2.start();
输出
1 2 3 4 5 6 19:19:37.547 [小王] c.TestMakeTea - 洗茶壶 19:19:37.547 [老王] c.TestMakeTea - 洗水壶 19:19:38.552 [小王] c.TestMakeTea - 洗茶杯 19:19:38.552 [老王] c.TestMakeTea - 烧开水 19:19:40.553 [小王] c.TestMakeTea - 拿茶叶 19:19:53.553 [小王] c.TestMakeTea - 泡茶
解法1 的缺陷:
上面模拟的是小王等老王的水烧开了,小王泡茶,如果反过来要实现老王等小王的茶叶拿来了,老王泡茶 呢?代码最好能适应两种情况
上面的两个线程其实是各执行各的,如果要模拟老王把水壶交给小王泡茶,或模拟小王把茶叶交给老王泡茶 呢
解法2:wait/notify 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class S2 { static String kettle = "冷水" ; static String tea = null ; static final Object lock = new Object (); static boolean maked = false ; public static void makeTea () { new Thread (() -> { log.debug("洗水壶" ); sleep(1 ); log.debug("烧开水" ); sleep(5 ); synchronized (lock) { kettle = "开水" ; lock.notifyAll(); while (tea == null ) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (!maked) { log.debug("拿({})泡({})" , kettle, tea); maked = true ; } } }, "老王" ).start(); new Thread (() -> { log.debug("洗茶壶" ); sleep(1 ); log.debug("洗茶杯" ); sleep(2 ); log.debug("拿茶叶" ); sleep(1 ); synchronized (lock) { tea = "花茶" ; lock.notifyAll(); while (kettle.equals("冷水" )) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (!maked) { log.debug("拿({})泡({})" , kettle, tea); maked = true ; } } }, "小王" ).start(); } }
输出
1 2 3 4 5 6 20 :04 :48.179 c.S2 [小王] - 洗茶壶20 :04 :48.179 c.S2 [老王] - 洗水壶20 :04 :49.185 c.S2 [老王] - 烧开水20 :04 :49.185 c.S2 [小王] - 洗茶杯20 :04 :51.185 c.S2 [小王] - 拿茶叶20 :04 :54.185 c.S2 [老王] - 拿(开水)泡(花茶)
解法2 解决了解法1 的问题,不过老王和小王需要相互等待,不如他们只负责各自的任务,泡茶交给第三人来做
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class S3 { static String kettle = "冷水" ; static String tea = null ; static final Object lock = new Object (); public static void makeTea () { new Thread (() -> { log.debug("洗水壶" ); sleep(1 ); log.debug("烧开水" ); sleep(5 ); synchronized (lock) { kettle = "开水" ; lock.notifyAll(); } }, "老王" ).start(); new Thread (() -> { log.debug("洗茶壶" ); sleep(1 ); log.debug("洗茶杯" ); sleep(2 ); log.debug("拿茶叶" ); sleep(1 ); synchronized (lock) { tea = "花茶" ; lock.notifyAll(); } }, "小王" ).start(); new Thread (() -> { synchronized (lock) { while (kettle.equals("冷水" ) || tea == null ) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } log.debug("拿({})泡({})" , kettle, tea); } }, "王夫人" ).start(); } }
输出
1 2 3 4 5 6 20:13:18.202 c.S3 [小王] - 洗茶壶 20:13:18.202 c.S3 [老王] - 洗水壶 20:13:19.206 c.S3 [小王] - 洗茶杯 20:13:19.206 c.S3 [老王] - 烧开水 20:13:21.206 c.S3 [小王] - 拿茶叶 20:13:24.207 c.S3 [王夫人] - 拿(开水)泡(花茶)
解法3:第三者协调 本章小结 本章的重点在于掌握
线程创建
线程重要 api,如 start,run,sleep,join,interrupt 等
线程状态
应用方面
异步调用:主线程执行期间,其它线程异步执行耗时操作
提高效率:并行计算,缩短运算时间
同步等待:join
统筹规划:合理使用线程,得到最优效果
原理方面
线程运行流程:栈、栈帧、上下文切换、程序计数器
Thread 两种创建方式 的源码
模式方面