线程同步方法之交换输出
来源:互联网 发布:sql执行视图命令 编辑:程序博客网 时间:2024/06/06 02:10
1 . 两个线程交换输出
2 . 使用的是同步方法
package com.qf.demo3;public class Test2 { public static void main(String[] args) { //创建资源类对象 Card2 card2 = new Card2(0); //创建两个操作类 Boy2 boy2 = new Boy2(card2); Girl2 girl2 = new Girl2(card2); //创建线程 Thread thread = new Thread(boy2); Thread thread2 = new Thread(girl2); //启动线程 thread.start(); thread2.start(); }}/** * true 男朋友存了钱了, 女朋友还没取 * false 女朋友去了钱了, 男朋友还没存 * *先想执行的是男朋友存钱 * flag = false * */// 资源类 里面有两个同步方法class Card2{ private int money = 0; public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public Card2(int money) { super(); this.money = money; } @Override public String toString() { return "Card2 [money=" + money + "]"; } //同步方法 存钱 public synchronized void save(){ if(money==1000){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } money +=1000; System.out.println("男朋友存了1000,还剩"+money); this.notify();// 唤醒对方 } //同步方法 取钱 public synchronized void take(){ if(money==0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } money-=1000; System.out.println("女朋友取了1000, 还剩下"+money); this.notify();// 唤醒对方 }}//操作类 中要有资源类对象 为了调用资源类的同步方法class Boy2 implements Runnable{ Card2 card; public Boy2(Card2 card) { this.card = card; } public void run() { for (int i = 0; i <10; i++) { card.save(); } }}class Girl2 implements Runnable{ Card2 card2; public Girl2(Card2 card2){ this.card2 = card2; } public void run() { for (int i = 0; i <10; i++) { card2.take(); } }}
阅读全文
0 0
- 线程同步方法之交换输出
- 线程同步代码块之交换输出
- 线程(6)--线程同步之同步方法和同步块
- C#之线程同步方法
- 线程同步---同步方法
- 线程同步方法之阻塞队列
- 13____java线程同步工具类之线程数据交换(Exchanger)
- 多线程(四)线程的同步之同步方法
- 线程之线程同步
- C#线程(三、线程同步技术之Join方法)
- 线程的同步-同步方法
- 线程同步的方法
- Windows线程同步方法
- 线程同步的方法
- 线程同步方法
- 线程同步的方法
- VC线程同步方法
- 线程同步的方法
- osmf grindPlayer的各种api。
- 缓冲区分析—ArcGIS API for JavaScript
- Differences between typedef and #define
- 竞争条件(race condition)
- Laravel:ORM模型为自己的方法建立Observer
- 线程同步方法之交换输出
- P1111 修复公路
- hankson的BT(bio-tech 变态)题 关于for循环边界
- 详细设计
- LeakCanary开源框架使用说明
- Unity Game视图不显示flare解决方法
- WPF 解决无边框产生的相关问题
- mybatis 异常 org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding
- FileOutputStream的简单用法