2个线程交替打印大小写英文字母

    使用wait() 和 nodify() 实现线程之间的切换。所以需要synchronized以及lock进行同步代码。因为俩个线程需要切换,必然需要一个标示flag决定线程是等待还是获得锁。

    volatile 的特性
    保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。(实现可见性)
    禁止进行指令重排序。(实现有序性)
    volatile 只能保证对单次读/写的原子性。i++ 这种操作不能保证原子性。

 

实现代码:

package com.example.test_mysql;

public class TestAa {

    private static volatile int flag = 0;
    private static Object o = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(() -> {

            for (int i =97;i<123;){
                synchronized (o){
                    if (flag==1){
                        System.out.printf(""+(char)i);
                        flag=0;
                        i++;
                        o.notify();
                    }else {
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }


                }
            }
        });

        Thread thread2 = new Thread(() -> {

            for (int i =65;i<91;){
                synchronized (o){
                    if (flag==0){
                        System.out.printf(""+(char)i);
                        flag=1;
                        i++;
                        o.notify();
                    }else {
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        });
        thread1.start();
        thread2.start();


    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值