线程的应用
如何应用多线程
继承 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:Javajdk1.8.0_91injava.exe "-javaagent:D:IntelliJ IDEA 2018.2.4libidea_rt.jar=52529:D:IntelliJ IDEA 2018.2.4in" -Dfile.encoding=UTF-8 -classpath "D:Javajdk1.8.0_91jrelibcharsets.jar;D:Javajdk1.8.0_91jrelibdeploy.jar;D:Javajdk1.8.0_91jrelibextaccess-bridge-32.jar;D:Javajdk1.8.0_91jrelibextcldrdata.jar;D:Javajdk1.8.0_91jrelibextdnsns.jar;D:Javajdk1.8.0_91jrelibextjaccess.jar;D:Javajdk1.8.0_91jrelibextjfxrt.jar;D:Javajdk1.8.0_91jrelibextlocaledata.jar;D:Javajdk1.8.0_91jrelibext ashorn.jar;D:Javajdk1.8.0_91jrelibextsunec.jar;D:Javajdk1.8.0_91jrelibextsunjce_provider.jar;D:Javajdk1.8.0_91jrelibextsunmscapi.jar;D:Javajdk1.8.0_91jrelibextsunpkcs11.jar;D:Javajdk1.8.0_91jrelibextzipfs.jar;D:Javajdk1.8.0_91jrelibjavaws.jar;D:Javajdk1.8.0_91jrelibjce.jar;D:Javajdk1.8.0_91jrelibjfr.jar;D:Javajdk1.8.0_91jrelibjfxswt.jar;D:Javajdk1.8.0_91jrelibjsse.jar;D:Javajdk1.8.0_91jrelibmanagement-agent.jar;D:Javajdk1.8.0_91jrelibplugin.jar;D:Javajdk1.8.0_91jrelib esources.jar;D:Javajdk1.8.0_91jrelib t.jar;D:IntelliJ IDEA ProjectsspringbootRabbitmq argetclasses;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-web2.0.0.RELEASEspring-boot-starter-web-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter2.0.0.RELEASEspring-boot-starter-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-logging2.0.0.RELEASEspring-boot-starter-logging-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositorychqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;D:DevlopeConfigmavenRepositorychqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;D:DevlopeConfigmavenRepositoryorgapachelogginglog4jlog4j-to-slf4j2.10.0log4j-to-slf4j-2.10.0.jar;D:DevlopeConfigmavenRepositoryorgapachelogginglog4jlog4j-api2.10.0log4j-api-2.10.0.jar;D:DevlopeConfigmavenRepositoryorgslf4jjul-to-slf4j1.7.25jul-to-slf4j-1.7.25.jar;D:DevlopeConfigmavenRepositoryjavaxannotationjavax.annotation-api1.3.2javax.annotation-api-1.3.2.jar;D:DevlopeConfigmavenRepositoryorgyamlsnakeyaml1.19snakeyaml-1.19.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-json2.0.0.RELEASEspring-boot-starter-json-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositorycomfasterxmljacksoncorejackson-databind2.9.4jackson-databind-2.9.4.jar;D:DevlopeConfigmavenRepositorycomfasterxmljacksoncorejackson-annotations2.9.0jackson-annotations-2.9.0.jar;D:DevlopeConfigmavenRepositorycomfasterxmljacksoncorejackson-core2.9.4jackson-core-2.9.4.jar;D:DevlopeConfigmavenRepositorycomfasterxmljacksondatatypejackson-datatype-jdk82.9.4jackson-datatype-jdk8-2.9.4.jar;D:DevlopeConfigmavenRepositorycomfasterxmljacksondatatypejackson-datatype-jsr3102.9.4jackson-datatype-jsr310-2.9.4.jar;D:DevlopeConfigmavenRepositorycomfasterxmljacksonmodulejackson-module-parameter-names2.9.4jackson-module-parameter-names-2.9.4.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-tomcat2.0.0.RELEASEspring-boot-starter-tomcat-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgapache omcatembed omcat-embed-core8.5.28 omcat-embed-core-8.5.28.jar;D:DevlopeConfigmavenRepositoryorgapache omcatembed omcat-embed-el8.5.28 omcat-embed-el-8.5.28.jar;D:DevlopeConfigmavenRepositoryorgapache omcatembed omcat-embed-websocket8.5.28 omcat-embed-websocket-8.5.28.jar;D:DevlopeConfigmavenRepositoryorghibernatevalidatorhibernate-validator6.0.7.Finalhibernate-validator-6.0.7.Final.jar;D:DevlopeConfigmavenRepositoryjavaxvalidationvalidation-api2.0.1.Finalvalidation-api-2.0.1.Final.jar;D:DevlopeConfigmavenRepositoryorgjbossloggingjboss-logging3.3.2.Finaljboss-logging-3.3.2.Final.jar;D:DevlopeConfigmavenRepositorycomfasterxmlclassmate1.3.4classmate-1.3.4.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-web5.0.4.RELEASEspring-web-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-beans5.0.4.RELEASEspring-beans-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-webmvc5.0.4.RELEASEspring-webmvc-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-aop5.0.4.RELEASEspring-aop-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-context5.0.4.RELEASEspring-context-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-expression5.0.4.RELEASEspring-expression-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgslf4jslf4j-api1.7.25slf4j-api-1.7.25.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-core5.0.4.RELEASEspring-core-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-jcl5.0.4.RELEASEspring-jcl-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-devtools2.0.0.RELEASEspring-boot-devtools-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot2.0.0.RELEASEspring-boot-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-autoconfigure2.0.0.RELEASEspring-boot-autoconfigure-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgprojectlomboklombok1.16.20lombok-1.16.20.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-data-jpa2.0.0.RELEASEspring-boot-starter-data-jpa-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-aop2.0.0.RELEASEspring-boot-starter-aop-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgaspectjaspectjweaver1.8.13aspectjweaver-1.8.13.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-jdbc2.0.0.RELEASEspring-boot-starter-jdbc-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositorycomzaxxerHikariCP2.7.8HikariCP-2.7.8.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-jdbc5.0.4.RELEASEspring-jdbc-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorghibernatehibernate-core5.2.14.Finalhibernate-core-5.2.14.Final.jar;D:DevlopeConfigmavenRepositoryorghibernatejavaxpersistencehibernate-jpa-2.1-api1.0.0.Finalhibernate-jpa-2.1-api-1.0.0.Final.jar;D:DevlopeConfigmavenRepositoryorgjavassistjavassist3.22.0-GAjavassist-3.22.0-GA.jar;D:DevlopeConfigmavenRepositoryantlrantlr2.7.7antlr-2.7.7.jar;D:DevlopeConfigmavenRepositoryorgjbossjandex2.0.3.Finaljandex-2.0.3.Final.jar;D:DevlopeConfigmavenRepositorydom4jdom4j1.6.1dom4j-1.6.1.jar;D:DevlopeConfigmavenRepositoryorghibernatecommonhibernate-commons-annotations5.0.1.Finalhibernate-commons-annotations-5.0.1.Final.jar;D:DevlopeConfigmavenRepositoryjavax ransactionjavax.transaction-api1.2javax.transaction-api-1.2.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkdataspring-data-jpa2.0.5.RELEASEspring-data-jpa-2.0.5.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkdataspring-data-commons2.0.5.RELEASEspring-data-commons-2.0.5.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-orm5.0.4.RELEASEspring-orm-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-tx5.0.4.RELEASEspring-tx-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-aspects5.0.4.RELEASEspring-aspects-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositorymysqlmysql-connector-java5.1.38mysql-connector-java-5.1.38.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkootspring-boot-starter-amqp2.0.0.RELEASEspring-boot-starter-amqp-2.0.0.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkspring-messaging5.0.4.RELEASEspring-messaging-5.0.4.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkamqpspring-rabbit2.0.2.RELEASEspring-rabbit-2.0.2.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgspringframeworkamqpspring-amqp2.0.2.RELEASEspring-amqp-2.0.2.RELEASE.jar;D:DevlopeConfigmavenRepositorycom abbitmqamqp-client5.1.2amqp-client-5.1.2.jar;D:DevlopeConfigmavenRepositorycom abbitmqhttp-client1.3.1.RELEASEhttp-client-1.3.1.RELEASE.jar;D:DevlopeConfigmavenRepositoryorgapachehttpcomponentshttpclient4.5.5httpclient-4.5.5.jar;D:DevlopeConfigmavenRepositoryorgapachehttpcomponentshttpcore4.4.9httpcore-4.4.9.jar;D:DevlopeConfigmavenRepositorycommons-codeccommons-codec1.11commons-codec-1.11.jar;D:DevlopeConfigmavenRepositoryorgspringframework etryspring-retry1.2.2.RELEASEspring-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/