2021-05-13

多线程简单通信问题:

(一道题解决简单交叉通信问题)

题目:要求两个线程,同时打印字母,每个线程都能连续打印3个字母。并且连续打印3个小写字母后,换成打印3个大写字母,再换成打印3个小写字母,以此类推。当字母循环到z之后,回到a。

(注:Char("65") A,Char("97") a 连续;例如:Char("65") A,Char("66") B)

效果如图:

 

代码处:

public class MyThread implements Runnable {

    private char letter = 'a'; //'a'是97,'A'是65;
    private boolean flag = true;//交叉的通信利用一个boolean属性来判断;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                this.notify();//唤醒被wait的线程;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }//使程序运行更有节奏;
                //把循环放在判断语句外,能够更有效的处理多次打印问题(内部判断);
                for (int i = 0; i < 3; i++) {
                    if (letter > 'z') {
                        letter = 'a';
                    }
                    if (flag) {
                        System.out.println(Thread.currentThread().getName() +
                                "->" + (letter++));//打印小写字母;本身就是char型;
                    } else {
                        System.out.println(Thread.currentThread().getName() +
                                "->" + (char) (letter++ - 32));//打印大写字母;
                    }
                }
                flag=!flag;//根据flag判断下一次执行哪一块的内容;(一定要放在wait的前面,保 
                          证能够使得下一次的程序的运行时候能够运行不一样的if语句中的内容;)
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }//交出锁,进入暂停;

            }
        }
    }
}

class test {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread one = new Thread(myThread);
        Thread two = new Thread(myThread);
        one.start();
        two.start();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值