线程同步方法之交换输出

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值