
线程的应用
如何应用多线程
继承 Thread 类创建线程
public class MyThread extends Thread { public void run() { System.out.println("MyThread.run()"); } } main中执行
MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); myThread1.start();
myThread2.start();
public class MyThread extends OtherClass implements Runnable { public void run() { System.out.println("MyThread.run()"); } }
带返回值的线程了。Java 中提供了这样的实现方式
public class CallableDemo implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
CallableDemo callableDemo = new CallableDemo();
Future<String> future = executorService.submit(callableDemo);
System.out.println(future.get());
executorService.shutdown();
} @Override
public String call() throws Exception {
int a = 1;
int b = 2;
System.out.println(a + b);
return "执行结果:" + (a + b);
}
}
Java 并发编程的基础
线程的生命周期

import java.util.concurrent.TimeUnit; public class ThreadStatus {
public static void main(String[] args) {
//TIME_WAITING
new Thread(() -> {
while (true) {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName()+"--TimeUnit.SECONDS.sleep(5)");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "timewaiting").start();
//WAITING,线程在 ThreadStatus 类锁上通过 wait 进行等待
new Thread(() -> {
while (true) {
synchronized (ThreadStatus.class) {
try {
ThreadStatus.class.wait();
System.out.println(Thread.currentThread().getName()+"--ThreadStatus.class.wait()");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Waiting").start();
//线程在 ThreadStatus 加锁后,不会释放锁
new Thread(new BlockedDemo(), "BlockDemo- 01").start();
new Thread(new BlockedDemo(), "BlockDemo- 02").start();
} static class BlockedDemo extends Thread {
public void run() {
synchronized (BlockedDemo.class) {
while (true) {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"--TimeUnit.SECONDS.sleep(3)");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
运行结果:
D:\Java\jdk1.8.0_91\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar=52529:D:\IntelliJ IDEA 2018.2.4\bin" -Dfile.encoding=UTF-8 -classpath "D:\Java\jdk1.8.0_91\jre\lib\charsets.jar;D:\Java\jdk1.8.0_91\jre\lib\deploy.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\access-bridge-32.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_91\jre\lib\javaws.jar;D:\Java\jdk1.8.0_91\jre\lib\jce.jar;D:\Java\jdk1.8.0_91\jre\lib\jfr.jar;D:\Java\jdk1.8.0_91\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_91\jre\lib\jsse.jar;D:\Java\jdk1.8.0_91\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_91\jre\lib\plugin.jar;D:\Java\jdk1.8.0_91\jre\lib\resources.jar;D:\Java\jdk1.8.0_91\jre\lib\rt.jar;D:\IntelliJ IDEA Projects\springbootRabbitmq\target\classes;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-web\2.0.0.RELEASE\spring-boot-starter-web-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter\2.0.0.RELEASE\spring-boot-starter-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-logging\2.0.0.RELEASE\spring-boot-starter-logging-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\DevlopeConfig\mavenRepository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\DevlopeConfig\mavenRepository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;D:\DevlopeConfig\mavenRepository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;D:\DevlopeConfig\mavenRepository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;D:\DevlopeConfig\mavenRepository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;D:\DevlopeConfig\mavenRepository\org\yaml\snakeyaml\1.19\snakeyaml-1.19.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-json\2.0.0.RELEASE\spring-boot-starter-json-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\jackson\core\jackson-databind\2.9.4\jackson-databind-2.9.4.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\jackson\core\jackson-core\2.9.4\jackson-core-2.9.4.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.4\jackson-datatype-jdk8-2.9.4.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.4\jackson-datatype-jsr310-2.9.4.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.4\jackson-module-parameter-names-2.9.4.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-tomcat\2.0.0.RELEASE\spring-boot-starter-tomcat-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\apache\tomcat\embed\tomcat-embed-core\8.5.28\tomcat-embed-core-8.5.28.jar;D:\DevlopeConfig\mavenRepository\org\apache\tomcat\embed\tomcat-embed-el\8.5.28\tomcat-embed-el-8.5.28.jar;D:\DevlopeConfig\mavenRepository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.28\tomcat-embed-websocket-8.5.28.jar;D:\DevlopeConfig\mavenRepository\org\hibernate\validator\hibernate-validator\6.0.7.Final\hibernate-validator-6.0.7.Final.jar;D:\DevlopeConfig\mavenRepository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;D:\DevlopeConfig\mavenRepository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;D:\DevlopeConfig\mavenRepository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-web\5.0.4.RELEASE\spring-web-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-beans\5.0.4.RELEASE\spring-beans-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-webmvc\5.0.4.RELEASE\spring-webmvc-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-aop\5.0.4.RELEASE\spring-aop-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-context\5.0.4.RELEASE\spring-context-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-expression\5.0.4.RELEASE\spring-expression-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-core\5.0.4.RELEASE\spring-core-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-jcl\5.0.4.RELEASE\spring-jcl-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-devtools\2.0.0.RELEASE\spring-boot-devtools-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot\2.0.0.RELEASE\spring-boot-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-autoconfigure\2.0.0.RELEASE\spring-boot-autoconfigure-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\projectlombok\lombok\1.16.20\lombok-1.16.20.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-data-jpa\2.0.0.RELEASE\spring-boot-starter-data-jpa-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-aop\2.0.0.RELEASE\spring-boot-starter-aop-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\aspectj\aspectjweaver\1.8.13\aspectjweaver-1.8.13.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-jdbc\2.0.0.RELEASE\spring-boot-starter-jdbc-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\com\zaxxer\HikariCP\2.7.8\HikariCP-2.7.8.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-jdbc\5.0.4.RELEASE\spring-jdbc-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\hibernate\hibernate-core\5.2.14.Final\hibernate-core-5.2.14.Final.jar;D:\DevlopeConfig\mavenRepository\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.0.Final\hibernate-jpa-2.1-api-1.0.0.Final.jar;D:\DevlopeConfig\mavenRepository\org\javassist\javassist\3.22.0-GA\javassist-3.22.0-GA.jar;D:\DevlopeConfig\mavenRepository\antlr\antlr\2.7.7\antlr-2.7.7.jar;D:\DevlopeConfig\mavenRepository\org\jboss\jandex\2.0.3.Final\jandex-2.0.3.Final.jar;D:\DevlopeConfig\mavenRepository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;D:\DevlopeConfig\mavenRepository\org\hibernate\common\hibernate-commons-annotations\5.0.1.Final\hibernate-commons-annotations-5.0.1.Final.jar;D:\DevlopeConfig\mavenRepository\javax\transaction\javax.transaction-api\1.2\javax.transaction-api-1.2.jar;D:\DevlopeConfig\mavenRepository\org\springframework\data\spring-data-jpa\2.0.5.RELEASE\spring-data-jpa-2.0.5.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\data\spring-data-commons\2.0.5.RELEASE\spring-data-commons-2.0.5.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-orm\5.0.4.RELEASE\spring-orm-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-tx\5.0.4.RELEASE\spring-tx-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-aspects\5.0.4.RELEASE\spring-aspects-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar;D:\DevlopeConfig\mavenRepository\org\springframework\boot\spring-boot-starter-amqp\2.0.0.RELEASE\spring-boot-starter-amqp-2.0.0.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\spring-messaging\5.0.4.RELEASE\spring-messaging-5.0.4.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\amqp\spring-rabbit\2.0.2.RELEASE\spring-rabbit-2.0.2.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\springframework\amqp\spring-amqp\2.0.2.RELEASE\spring-amqp-2.0.2.RELEASE.jar;D:\DevlopeConfig\mavenRepository\com\rabbitmq\amqp-client\5.1.2\amqp-client-5.1.2.jar;D:\DevlopeConfig\mavenRepository\com\rabbitmq\http-client\1.3.1.RELEASE\http-client-1.3.1.RELEASE.jar;D:\DevlopeConfig\mavenRepository\org\apache\httpcomponents\httpclient\4.5.5\httpclient-4.5.5.jar;D:\DevlopeConfig\mavenRepository\org\apache\httpcomponents\httpcore\4.4.9\httpcore-4.4.9.jar;D:\DevlopeConfig\mavenRepository\commons-codec\commons-codec\1.11\commons-codec-1.11.jar;D:\DevlopeConfig\mavenRepository\org\springframework\retry\spring-retry\1.2.2.RELEASE\spring-retry-1.2.2.RELEASE.jar" com.lf.Configuration.ThreadStatus
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
timewaiting--TimeUnit.SECONDS.sleep(5)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
timewaiting--TimeUnit.SECONDS.sleep(5)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
timewaiting--TimeUnit.SECONDS.sleep(5)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
timewaiting--TimeUnit.SECONDS.sleep(5)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
timewaiting--TimeUnit.SECONDS.sleep(5)
BlockDemo- 01--TimeUnit.SECONDS.sleep(3)
4384 ThreadStatus
8084
4360 Jps
bash-3.1$ jstack 4384
2020-05-06 23:20:41
Full thread dump Java HotSpot(TM) Client VM (25.91-b14 mixed mode): "DestroyJavaVM" #15 prio=5 os_prio=0 tid=0x0342b400 nid=0x30e0 waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE "BlockDemo- 02" #14 prio=5 os_prio=0 tid=0x161d1c00 nid=0x3164 waiting for monitor entry [0x167cf000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.lf.Configuration.ThreadStatus$BlockedDemo.run(ThreadStatus.java:41)
- waiting to lock <0x05661d28> (a java.lang.Class for com.lf.Configuration.ThreadStatus$BlockedDemo)
at java.lang.Thread.run(Thread.java:745) "BlockDemo- 01" #12 prio=5 os_prio=0 tid=0x161cf000 nid=0x24c8 waiting on condition [0x1673f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
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 com.lf.Configuration.ThreadStatus$BlockedDemo.run(ThreadStatus.java:41)
- locked <0x05661d28> (a java.lang.Class for com.lf.Configuration.ThreadStatus$BlockedDemo)
at java.lang.Thread.run(Thread.java:745) "Waiting" #10 prio=5 os_prio=0 tid=0x161cdc00 nid=0x1bd8 in Object.wait() [0x166af000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x05ad2000> (a java.lang.Class for com.lf.Configuration.ThreadStatus)
at java.lang.Object.wait(Object.java:502)
at com.lf.Configuration.ThreadStatus.lambda$main$1(ThreadStatus.java:23)
- locked <0x05ad2000> (a java.lang.Class for com.lf.Configuration.ThreadStatus)
at com.lf.Configuration.ThreadStatus$$Lambda$2/30452001.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745) "timewaiting" #9 prio=5 os_prio=0 tid=0x161cd000 nid=0x1298 waiting on condition [0x1661f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
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 com.lf.Configuration.ThreadStatus.lambda$main$0(ThreadStatus.java:11)
at com.lf.Configuration.ThreadStatus$$Lambda$1/8844017.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745) "Service Thread" #8 daemon prio=9 os_prio=0 tid=0x160a3c00 nid=0x1e24 runnable [0x00000000]
java.lang.Thread.State: RUNNABLE "C1 CompilerThread0" #7 daemon prio=9 os_prio=2 tid=0x16063c00 nid=0x1a64 waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE "Monitor Ctrl-Break" #6 daemon prio=5 os_prio=0 tid=0x160a6800 nid=0xc58 runnable [0x163df000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
- locked <0x05aee288> (a java.io.InputStreamReader)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
- locked <0x05aee288> (a java.io.InputStreamReader)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64) "Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x15a91000 nid=0x1230 waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE "Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x15a8f800 nid=0x3150 runnable [0x00000000]
java.lang.Thread.State: RUNNABLE "Finalizer" #3 daemon prio=8 os_prio=1 tid=0x15a7d000 nid=0x11f8 in Object.wait() [0x15dcf000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x05aee758> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
- locked <0x05aee758> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209) "Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x15a67400 nid=0x1b8c in Object.wait() [0x15d3f000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x05aee8f8> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:502)
at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
- locked <0x05aee8f8> (a java.lang.ref.Reference$Lock)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153) "VM Thread" os_prio=2 tid=0x15a61400 nid=0x1ec4 runnable "VM Periodic Task Thread" os_prio=2 tid=0x1619ac00 nid=0xfe0 waiting on condition JNI global references: 232 bash-3.1$
线程的启动
更深入的。。。囧
线程的终止
public class InterruptDemo {
private static int i; public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) { //默认情况下isInterrupted 返回 false、通过 thread.interrupt 变成了 true
i++;
}
System.out.println("Num:" + i);
}, "interruptDemo");
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt(); //加和不加的效果
}
}
加了,线程运行一会会被打断,并输出Num值
不加,线程会一直运行
public class InterruptDemo2 {
private static int i; public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("before:" + Thread.currentThread().isInterrupted()); Thread.interrupted(); //对线程进行复位,由 true 变成 false System.out.println("after:" + Thread.currentThread().isInterrupted());
}
}
}, "interruptDemo");
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
}
}
运行结果:
before:true
after:false
除了通过 Thread.interrupted 方法对线程中断标识进行复 位 以 外 , 还 有 一 种 被 动 复 位 的 场 景 , 就 是 对 抛 出 InterruptedException 异 常 的 方 法 ,
在 InterruptedException 抛出之前,JVM 会先把线程的中断 标识位清除,然后才会抛出 InterruptedException,这个时 候如果调用 isInterrupted 方法,
将会返回 false 分别通过下面两个 demo 来演示复位的效果
demo1
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
i++;
}
System.out.println("Num:" + i);
}, "interruptDemo");
thread.start(); TimeUnit.SECONDS.sleep(1); thread.interrupt(); System.out.println(thread.isInterrupted());
}
输出:
true
Num:36375203
private static int i;
demo2
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Num:" + i);
}, "interruptDemo"); thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
System.out.println(thread.isInterrupted());
}
输出:
false
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 com.lf.Configuration.InterruptDemoCompare.lambda$main$0(InterruptDemoCompare.java:12)
at java.lang.Thread.run(Thread.java:745)

这个方法比较简单,直接调用了 Thread::interrupt(thr)这个方法,这个方法的定义在 Thread.cpp 文件中,代码如下
Thread::interrupt 方法调用了 os::interrupt 方法,这个是调用平台的 interrupt 方法,这个方法的实现是在 os_*.cpp
set_interrupted(true)实际上就是调用 osThread.hpp 中的
找到 Thread.sleep 这个操作在 jdk 中的源码体现,怎么找?相信如果前面大家有认真看的话,应该能很快找到,
代码在 jvm.cpp 文件中

注意上面加了中文注释的地方的代码,先判断is_interrupted 的 状 态 , 然 后 抛 出 一 个
package com.lf.Configuration; import lombok.Getter;
import lombok.Setter;
import lombok.ToString; @ToString
public class Request {
@Getter
@Setter
private String name; }
package com.lf.Configuration; public interface RequestProcessor { void processRequest(Request request); }
package com.lf.Configuration; import java.util.concurrent.LinkedBlockingQueue; public class SaveProcessor extends Thread implements RequestProcessor {
LinkedBlockingQueue<Request> requests = new LinkedBlockingQueue<Request>(); @Override
public void run() {
while (true) {
try {
//队列为空,阻塞等待。
//队列不为空,从队首获取并移除一个元素,如果消费后还有元素在队列中,继续唤醒下一个消费线程进行元素移除。
// 如果放之前队列是满元素的情况,移除完后要唤醒生产线程进行添加元素
System.out.println("SaveProcessor: begin" );
Request request = requests.take();// System.out.println("save request info:" + request);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} //处理请求
public void processRequest(Request request) {
requests.add(request);
}
}
package com.lf.Configuration; import java.util.concurrent.LinkedBlockingQueue; public class PrintProcessor extends Thread implements RequestProcessor { LinkedBlockingQueue<Request> requests = new LinkedBlockingQueue<>(); private final RequestProcessor nextProcessor; public PrintProcessor(RequestProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
} @Override
public void run() {
while (true) {
try {
//队列为空,阻塞等待。
//队列不为空,从队首获取并移除一个元素,如果消费后还有元素在队列中,继续唤醒下一个消费线程进行元素移除。
// 如果放之前队列是满元素的情况,移除完后要唤醒生产线程进行添加元素
System.out.println("PrintProcessor: begin" );
Request request = requests.take();
System.out.println("print data:" + request.getName());
nextProcessor.processRequest(request);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} //处理请求
public void processRequest(Request request) {
requests.add(request);
}
}
package com.lf.Configuration; public class Main { PrintProcessor printProcessor; protected Main() {
SaveProcessor saveProcessor = new SaveProcessor();
saveProcessor.start();
printProcessor = new PrintProcessor(saveProcessor);
printProcessor.start();
} private void doTest(Request request) {
printProcessor.processRequest(request);
} public static void main(String[] args) {
Request request = new Request();
request.setName("lf");
new Main().doTest(request);
}
}
运行结果:
SaveProcessor: begin
PrintProcessor: begin
print data:lf
PrintProcessor: begin
save request info:Request(name=lf)
SaveProcessor: begin
附一个java多线程链接:http://blog.cuzz.site/2019/04/16/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/