多线程交替打印(奇偶 / 0102...)

该博客探讨了如何使用`synchronized`关键字和`juc.Lock`实现多线程交替打印0102...的场景。首先展示了一个使用`synchronized`的示例,通过`wait()`和`notifyAll()`方法实现线程间的同步。接着,使用`ReentrantLock`和`Condition`接口的示例展示了更精确的线程唤醒控制,实现了类似的功能,但具有更好的灵活性。
摘要由CSDN通过智能技术生成

多线程交替打印(奇偶 / 0102…)

synchronized解决

public class EvenOdd {
    public static void main(String[] args) {
        EvenOddPrint evenOdd = new EvenOddPrint();

        new Thread(() -> {
            try {
                evenOdd.evenPrint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "evenPrint").start();

        new Thread(() -> {
            try {
                evenOdd.oddPrint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "oddPrint").start();
    }

}

class EvenOddPrint {
    private int i = 0;

    public synchronized void evenPrint() throws InterruptedException {
        while (i < 100) {
            if (i % 2 == 0) {
                this.wait();
            }
            
            System.out.println(Thread.currentThread().getName() + "---> " + i);
            i += 1;
            this.notifyAll();
        }
    }

    public synchronized void oddPrint() throws InterruptedException {
        while (i <= 100) {
            if (i % 2 != 0) {
                this.wait();
            }
            
 			System.out.println(Thread.currentThread().getName() + " ---> " + i);
            i += 1;
            this.notifyAll();
        }
    }
}

三个线程打印01020304…

synchronized不能唤醒指定线程,采用juc.Lock

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ZeroOneTwo {
    public static void main(String[] args) {
        ZeroOneTwoPrint print = new ZeroOneTwoPrint();
        new Thread(() -> {
            try {
                print.zeroPrint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "zero").start();
        new Thread(() -> {
            try {
                print.evenPrint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "even").start();
        new Thread(() -> {
            try {
                print.oddPrint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "odd").start();
    }
}

class ZeroOneTwoPrint {
    private int i = 1;
    private int flag = 0;
    private static final int MAX_NUM = 100;

    private Lock lock = new ReentrantLock();
    private Condition condition0 = lock.newCondition();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();

    public void zeroPrint() throws InterruptedException {
        lock.lock();
        try {
            while (i < MAX_NUM) {
                while (flag != 0) {
                    condition0.await();
                }

                System.out.println(Thread.currentThread().getName() + " ---> " + 0);
                flag = 1;
                if (i % 2 != 0) {
                    condition1.signal();
                } else {
                    condition2.signal();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void evenPrint() throws InterruptedException {
        lock.lock();

        try {
            while (i < MAX_NUM) {
                while (i % 2 == 0) {
                    condition1.await();
                }

                System.out.println(Thread.currentThread().getName() + " ---> " + i);
                i ++;
                flag = 0;
                condition0.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void oddPrint() throws InterruptedException {
        lock.lock();

        try {
            while (i < MAX_NUM) {
                while (i % 2 != 0) {
                    condition2.await();
                }

                System.out.println(Thread.currentThread().getName() + " ---> " + i);
                i ++;
                flag = 0;
                condition0.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值