两个线程交替执行,一个输出偶数,一个输出奇数

avatar 2020年08月20日15:37:14 6 2597 views
博主分享免费Java教学视频,B站账号:Java刘哥

方法一、

使用 synchronized 实现

public class Demo {

    public synchronized void print1() {
        for (int i = 1; i <= 100; i += 2) {
            System.out.println(Thread.currentThread().getName()+": "+i);
            this.notify();
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized void print2() {
        for (int i = 2; i <= 100; i += 2) {
            System.out.println(Thread.currentThread().getName()+": "+i);
            this.notify();
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(() -> demo.print1()).start();
        new Thread(() -> demo.print2()).start();
    }
}

稍微说一下 wait() 和 notify 的作用

this.wait() :立即将当前线程挂起,释放 this 锁

this.notify() :唤醒一个被挂起线程(被唤醒后不一定能立即获得锁,需要等获取锁后才能继续执行)

 

 

方法二、

基于 CAS 实现

public class Demo2 {

    volatile static boolean flag = false;
    volatile static int num = 0;

    public void print1() {
        while (num < 100) {
            if (!flag && ++num % 2 == 1) {
                System.out.println(Thread.currentThread().getName() + ": " + num);
                flag = true;
            }
        }
    }
    public void print2() {
        while (num < 100) {
            if (flag && ++num % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ": " + num);
                flag = false;
            }
        }
    }

    public static void main(String[] args) {
        Demo2 demo = new Demo2();
        new Thread(() -> demo.print1()).start();
        new Thread(() -> demo.print2()).start();
    }
}

我们通过使用 CAS,避免线程的上下文切换,然后呢,使用一个 volatile 的 boolean 变量,保证不会出现可见性问题,记住,这个 flag 一定要是 volatile 的

 

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0