当前位置:网站首页>模拟线程通信
模拟线程通信
2022-07-06 23:09:00 【洋啊桑815】
1:多个线程共同操作的共享资源:User类 含有money存款,以及存钱与取钱的方法
public class User {
private double money;
public User() {
}
public User(double money) {
this.money = money;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
/***
* 存钱的方法
* @param money
*/
public synchronized void updateMoney(Double money){
try {
System.out.println(Thread.currentThread()+"进来了");
Thread.sleep(2000);
if(this.money==0){
this.money+=money;
System.out.println(Thread.currentThread()+"存钱"+money);
this.notifyAll();
this.wait();
}else{
this.notifyAll();
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/***
* 取钱的方法的方法
* @param v
*/
public synchronized void deleteMoney(double v) {
try {
System.out.println(Thread.currentThread()+"进来了");
Thread.sleep(2000);
if(this.money>=v){
this.money-=v;
System.out.println(Thread.currentThread()+"取钱"+v);
this.notifyAll();
this.wait();
}else{
this.notifyAll();
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
创建两个线程:存款线程与取款线程
//取钱
public class GetThread extends Thread{
private User user;
public GetThread(User user,String name) {
super(name);
this.user = user;
}
@Override
public void run(){
while (true) {
user.deleteMoney(1000.0);
}
}
}//存钱
public class SetThread extends Thread {
private User user;
public SetThread(User user,String name) {
super(name);
this.user = user;
}
@Override
public void run(){
while (true) {
user.updateMoney(10000.0);
}
}
}
主方法:
public class TestDamo {
public static void main(String[] args) {
User user=new User(1000);
new GetThread(user,"小明1").start();
new GetThread(user,"小明2").start();
new SetThread(user,"小红1").start();
new SetThread(user,"小红2").start();
new SetThread(user,"小红3").start();
}
}边栏推荐
- 指针与数组在函数中输入实现逆序输出
- How to choose an offer and what factors should be considered
- Auto.js 获取手机所有app名字
- National meteorological data / rainfall distribution data / solar radiation data /npp net primary productivity data / vegetation coverage data
- U++ 游戏类 学习笔记
- 最全常用高数公式
- 当 Knative 遇见 WebAssembly
- JS variable case output user name
- ThinkPHP关联预载入with
- Operand of null-aware operation ‘!‘ has type ‘SchedulerBinding‘ which excludes null.
猜你喜欢
随机推荐
app内嵌h5---iphone软键盘遮挡输入文字
[hand torn STL] list
The execution order of return in JS' try catch finally
Weebly mobile website editor mobile browsing New Era
LabVIEW在打开一个新的引用,提示内存已满
5G VoNR+之IMS Data Channel概念
How to design API interface and realize unified format return?
R descriptive statistics and hypothesis testing
《二》标签
STM32F103实现IAP在线升级应用程序
Markdown编辑器
使用知云阅读器翻译统计遗传学书籍
高手勿进!写给初中级程序员以及还在大学修炼的“准程序员”的成长秘籍
Pointer and array are input in function to realize reverse order output
Operand of null-aware operation ‘!‘ has type ‘SchedulerBinding‘ which excludes null.
Error: No named parameter with the name ‘foregroundColor‘
如何设计 API 接口,实现统一格式返回?
【ArcGIS教程】专题图制作-人口密度分布图——人口密度分析
最全常用高数公式
IMS data channel concept of 5g vonr+








