线程同步(标志位看做成共享资源)

1 .
需求:
*自己写一个标志位
* flag = true 打印了数字了还没打印字母, 此时 应该 让数字等着 打印 字母
* false 打印了字母了 还没打印数字,此时 应让 字母等着, 打印数字

package com.qf.demo3;
/**
 * 需求:
 * A12B34C56......Z5152
 * 
 * 两个线程
 * 一个字母 
 * 一个数字
 * 
 *用到 线程间通信
 *
 *wait
 *notify
 *
 *
 *money  ==1000  == 0
 *
 *自己写一个标志位
 *  flag = true  打印了数字了还没打印字母, 此时 应该 让数字等着   打印 字母
 *         false  打印了字母了 还没打印数字,此时 应让 字母等着, 打印数字
 *  
 */
public class Test3 {

    public static void main(String[] args) {
        Resurce resurce = new Resurce();

        Number number = new Number(resurce);
        Letter letter = new Letter(resurce);

        Thread thread = new Thread(number);
        Thread thread2 = new Thread(letter);

        thread.start();
        thread2.start();
    }
}



//true 打印了数字 还没打印字母
// false  打印了 字母还没有打印数字



class Resurce {
    boolean flag = true;   //true 打印了数字 还没打印字母
                            // false  打印了 字母还没有打印数字
    public synchronized void printNumber(int num){
        // 1判断是否应该wait
        if(flag == true){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // 如果没有进入wait 目前来说是false 应该打印数字
        System.out.print(num+""+(num+1));//
        //改变状态
        flag = true;
        this.notify();
    }
    public synchronized void printLetter(int letter){
        if(flag == false){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // 如果没有进入 wait 证明现在是true ,应该打印字母
        System.out.print((char)letter);
        // 已经打印过了字母了. 应该吧状态改变成为false
        flag = false;
        this.notify();
    }
}

class Number implements Runnable{
    Resurce resurce;
    public Number(Resurce resurce) {
        this.resurce = resurce;
    }
    public void run() {
        for (int i = 1; i <= 52; i+=2) {
            resurce.printNumber(i);
        }
    }
}

class Letter implements Runnable{
    Resurce resurce;
    public Letter(Resurce resurce) {
        this.resurce = resurce;
    }
    public void run() {
        for (int i = 0; i < 26; i++) {
            resurce.printLetter(65+i);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值