多线程轮流交替执行三种实现方法

第一种方法:采用公平锁实现

思路及其简单:

  1. A线程拿到锁,执行代码
  2. B线程拿到锁,执行代码
  3. A线程拿到锁,执行代码
  4. ......
public class FairLockDemo {

    public static void main(String[] args) {

        Runnable target = new Runnable(){

            int i = 10;

            // 利用公平锁
            private ReentrantLock lock = new ReentrantLock(true);

            @Override
            public void run() {

                while (i >= 0) {
                    try{
                        lock.lock();
                        if(i % 2 == 0){
                            System.out.println("A");
                        }else {
                            System.out.println("B");
                        }
                        i--;
                    }finally{
                        lock.unlock();
                    }
                }
            }
        };

        Thread t1 = new Thread(target, "thread-1");
        Thread t2 = new Thread(target, "thread-2");
        t1.start();
        t2.start();
    }
}


第二种方法:采用synchronized对象锁 + wait + notify实现

思路比较复杂,值得细细揣摩:

  • 关键点:每个线程都有获得锁的权利
  • 1、满足if条件的,wait等待释放锁
  • 2、不满足if条件的,执行业务代码
public class TestThead {

    // 对象锁
    private static Object obj = new Object();
    private static volatile int num = 10;

    public static void main(String[] args) {

        new Thread(new Runnable() {           // 匿名内部类
            @Override
            public void run() {
                synchronized (obj) {
                    while(num > 0){
                        if(num % 2 == 0){
                            try {
                                obj.wait();   // 释放锁进入等待队列(等待池),线程2获取到对象锁
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        num--;
                        if(num >= 0){
                            System.out.println("B");
                        }
                        obj.notify();         // 唤醒等待队列中线程2进入锁池竞争对象锁
                    }
                }
            }
        }, "thread1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (obj) {
                    while(num > 0){
                        if(num % 2 != 0){
                            try {
                                obj.wait();   // 释放锁进入等待队列(等待池),线程1获取到对象锁
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        num--;
                        if(num >= 0){
                            System.out.println("A");
                        }
                        obj.notify();       // 唤醒等待队列中线程1进入锁池竞争对象锁
                    }
                }
            }
        }, "thread2").start();
    }
}


3、采用Lock和Condition实现

思路:

  • 其实和上面的思路差不多
  • 只不过上面用了同一个对象锁,思考起来比较麻烦
  • 这里采用了两个锁,轮流开闭,思考起来很方便
public class LockCond {

    private static volatile int count = 10;
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        Condition c1 = lock.newCondition();
        Condition c2 = lock.newCondition();

        new Thread(()->{
            while(count > 0) {
                lock.lock();
                try {
                    if(count % 2 == 0) {
                        System.out.println("A");
                        c1.await();
                    }
                    //唤醒线程2
                    c2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    count--;
                    lock.unlock();
                }
            }
        }) .start();

        new Thread(()->{
            while(count > 0) {
                lock.lock();
                try {
                    if(count % 2 == 1) {
                        System.out.println("B");
                        c2.await();
                    }
                    //唤醒线程1
                    c1.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    count--;
                    lock.unlock();
                }
            }
        }) .start();
    }
}

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java多线程交替执行可以通过使用synchronized关键字和wait()、notify()方法实现。具体实现方式可以参考以下步骤: 1. 创建两个线程对象并启动它们。 2. 在run()方法中使用synchronized关键字锁定一个共享对象,例如一个字符串对象。 3. 在第一个线程中打印奇数,然后调用共享对象的notify()方法唤醒等待的线程。 4. 在第二个线程中打印偶数,然后调用共享对象的notify()方法唤醒等待的线程。 5. 在每个线程中使用wait()方法使线程等待,直到被唤醒。 6. 在main()方法中使用join()方法等待两个线程执行完毕。 下面是一个简单的示例代码: ``` public class ThreadTest { private static Object lock = new Object(); private static int num = 1; private static boolean flag = true; public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { while (num <= 100) { synchronized (lock) { if (!flag) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println(Thread.currentThread().getName() + ": " + num); num++; flag = false; lock.notify(); } } } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (num <= 100) { synchronized (lock) { if (flag) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println(Thread.currentThread().getName() + ": " + num); num++; flag = true; lock.notify(); } } } } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值