线程同步方法之交换输出

来源:互联网 发布: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();        }    }}
原创粉丝点击