通信方式
要想实现多个线程之间的协同,如:线程执行先后顺序,获取某个线程执行的结果等等.
涉及到线程之间相互通信,分为下面四类:
1.文件共享
2.网络共享
3.共享变量
4.jdk提供的线程协调api
细分为:suspend/resume wait/notify park/unpark
这篇博客主要是讲解jdk提供的线程协调api
线程协作
jdk中对于需要多线程协作完成某一任务的场景,提供了对应api支持
多线程协作的经典场景是:生产者-消费者模型(线程阻塞,线程唤醒)
示例:线程1去买包子,没有包子,则不再执行。线程2生产出包子,通知线程1继续执行
suspend和resume
#API-被弃用的suspend和resume
作用:条用suspend挂起目标线程,通过resume可以恢复线程执行
被弃用的主要原因是,容易写出死锁的代码,所以用wait/notify和park/unpark机制对他进行替代
首先先写正确的代码
package demo2;
public class demo7 {
/**包子店**/
public static Object baozidian=null;
//限制性suspend,在执行resume。反之则死锁
public void suspendResumeTest() throws Exception{
//启动线程
Thread consumerThread=new Thread(()->{
if(baozidian==null) {
System.out.println("1.没有包子,进入等待");
Thread.currentThread().suspend();
}
System.out.println("2.买到包子,回家");
});
consumerThread.start();
//3秒之后,生产一个包子
Thread.sleep(3000L);
baozidian=new Object();
consumerThread.resume();
System.out.println("3.通知消费者");
}
public static void main(String[] args) throws Exception {
new demo7().suspendResumeTest();
}
}
死锁情况
但是可能会出现两种死锁情况:
产生死锁一:同步代码中使用
产生死锁二:suspend比resume后执行
同步代码中使用
package demo2;
public class demo7 {
/**包子店**/
public static Object baozidian=null;
public void suspendResumeTest() throws Exception{
//启动线程
Thread consumerThread=new Thread(()->{
if(baozidian==null) {
System.out.println("1.没有包子,进入等待");
//当前线程拿到锁,然后挂起
synchronized (this){
Thread.currentThread().suspend();
}
}
System.out.println("2.买到包子,回家");
});
consumerThread.start();
//3秒之后,生产一个包子
Thread.sleep(3000L);
//争取到锁以后,在恢复consumerThread 拿不到锁,无法进行唤醒
synchronized (this){
consumerThread.resume();
}
System.out.println("3.通知消费者");
}
public static void main(String[] args) throws Exception {
new demo7().suspendResumeTest();
}
}
主要是争取到锁的时候,在恢复consumerThread 拿不到锁,无法进行唤醒。导致死锁
suspend比resume后执行
package demo2;
public class demo7 {
/**包子店**/
public static Object baozidian=null;
//限制性suspend,在执行resume。反之则死锁
public void suspendResumeTest() throws Exception{
//启动线程
Thread consumerThread=new Thread(()->{
if(baozidian==null) {
System.out.println("1.没有包子,进入等待");
try{//为这个线程加上一点延时
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
//这里的挂起执行在resume后面
Thread.currentThread().suspend(); //方法没有调用 但是调用唤醒的已经调用过了
}
System.out.println("2.买到包子,回家");
});
consumerThread.start();
//3秒之后,生产一个包子
Thread.sleep(3000L);
baozidian=new Object();
consumerThread.resume();
System.out.println("3.通知消费者");
consumerThread.join();
}
public static void main(String[] args) throws Exception {
new demo7().suspendResumeTest();
}
}
这篇就先分享到这里,下一篇我们来讲讲现在推荐使用的两种方式