java------线程通信实例
来源:互联网 发布:华硕笔记本怎么优化 编辑:程序博客网 时间:2024/06/07 13:17
package lyfpractice.src.com.comunication;/** * Created by fangjiejie on 2016/12/21. */public class Account { String name; double money; public Account(String name, double money) { this.name = name; this.money = money; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } boolean flag=false;//可存不可取,true可取不可存 void savemoney(double money){//存钱 synchronized (this){ if(flag==true){ try { System.out.print(Thread.currentThread().getName()); System.out.println("现在不能存!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ System.out.print(Thread.currentThread().getName()); this.setMoney(this.getMoney() + money); System.out.println("已经存"+money+"元"); } flag=true; notifyAll(); } } void takemoney(double money){//取钱 synchronized (this){ if(flag==false){ try { System.out.print(Thread.currentThread().getName()); System.out.println("现在不能取!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ if(this.getMoney()<money){ System.out.print(Thread.currentThread().getName()); System.out.println("余额不足!"); } else { System.out.print(Thread.currentThread().getName()); System.out.println("已经取到"+money+"元"); this.setMoney(this.getMoney() - money); } } flag=false; notifyAll(); } }}
package lyfpractice.src.com.comunication;/** * Created by fangjiejie on 2016/12/21. */public class Save extends Thread{ String people; Account account; double m; public Save(String people,double m, Account account) { this.people = people; this.m=m; this.account = account; } @Override public void run() { account.savemoney(m); }}
package lyfpractice.src.com.comunication;/** * Created by fangjiejie on 2016/12/21. */public class Take extends Thread{ String people; Account account; double m; public Take(String people,double m, Account account) { this.people = people; this.m=m; this.account = account; } @Override public void run() { account.takemoney(m); }}
package lyfpractice.src.com.comunication;/** * Created by fangjiejie on 2016/12/21. */public class test { public static void main(String[] args) { Account l=new Account("lyf",0); new Save("mm",100,l).start(); Save a=new Save("dd",100,l); a.start(); new Save("gg",100,l).start(); new Take("dd",100,l).start(); new Save("gg",100,l).start(); }}
0 0
- java------线程通信实例
- Java多线程通信、同步卖票实例--线程安全、详细注释
- 线程间的通信实例
- JAVA线程-线程间通信
- java线程通信
- java 线程间通信
- Java.线程通信
- java线程通信
- java线程通信复习
- Java 线程通信
- Java线程通信机制
- java线程间通信
- Java线程通信 (一)
- java 线程通信
- Java线程通信
- Java线程间通信
- java 线程通信
- Java复习--线程通信
- TQ2440开发板学习纪实(3)--- 设置时钟频率,让CPU运行的更快
- 实验_天气
- Delphi基本图像处理方法汇总
- protobuf3 环境配置与编译
- Unity3D游戏开发之“重写Unity Android Splash,实现启动无黑屏
- java------线程通信实例
- 浅析数据一致性
- lajp
- Unity3d 多线程编程 线程和主线程(UI)交互实现问题
- 网络IO之阻塞、非阻塞、同步、异步总结
- android颜色对应的颜色表 xml配置值
- 九九乘法表的代码
- android开发 流行框架
- Unity3D游戏开发之“预加载场景,瞬间过图