阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

线程间的通信

261次阅读
没有评论

共计 1206 个字符,预计需要花费 4 分钟才能阅读完成。

1、线程间通信

针对同一个资源的操作有不同种类的线程
举例:卖票有进的,也有出的。

通过设置线程 (生产者) 和获取线程 (消费者) 针对同一个学生对象进行操作

线程间通信的代码改进

通过等待唤醒机制实现数据依次出现
把同步代码块改进为同步方法实现

线程的状态转换图

线程间的通信

public class GetThread implements Runnable {private Student s;
public GetThread(Student s) {this.s = s;
}
@Override
public void run() {while (true) {s.get();
}
}
}
public class SetThread implements Runnable {private Student s;
private int x = 0;
public SetThread(Student s) {this.s = s;
}
@Override
public void run() {while (true) {if (x % 2 == 0) {s.set("林青霞", 27);
} else {s.set("刘意", 30);
}
x++;
}
}
}
public class Student {private String name;
private int age;
private boolean flag; // 默认情况是没有数据,如果是 true,说明有数据
public synchronized void set(String name, int age) {// 如果有数据,就等待
if (this.flag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();
}
}
// 设置数据
this.name = name;
this.age = age;
// 修改标记
this.flag = true;
this.notify();}
public synchronized void get() {// 如果没有数据,就等待
if (!this.flag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();
}
}
// 获取数据
System.out.println(this.name + "---" + this.age);
// 修改标记
this.flag = false;
this.notify();}
}
public class StudentDemo {public static void main(String[] args) {// 创建资源
Student s = new Student();
// 设置和获取的类
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
// 线程类
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
// 启动线程
t1.start();
t2.start();}
}

正文完
星哥玩云-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-06-06发表,共计1206字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中