【多线程】线程交替执行

文章展示了三种在Java中实现线程交替执行的方法:1)使用wait和notify,通过共享对象的锁机制控制线程执行顺序;2)利用Condition的await和signal方法,实现更细粒度的线程同步;3)使用LockSupport的park和unpark函数进行线程的暂停和恢复。每种方法都通过循环和条件判断保证了线程的交替运行。
摘要由CSDN通过智能技术生成
1.wait与notify实现
package com.learning.thread_order;

import java.util.concurrent.locks.*;
/**
 * @Author wangyouhui
 * @Description 线程交替执行
 **/
public class ThreadInTurnExecute {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1, 5);
        Thread thread1 = new Thread(()->{
            waitNotify.print("线程1执行", 1, 2);
        });
        Thread thread2 = new Thread(()->{
            waitNotify.print("线程2执行", 2, 3);
        });
        Thread thread3 = new Thread(()->{
            waitNotify.print("线程3执行", 3, 1);
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class WaitNotify{
    // 等待标记
    private int flag;
    // 循环次数
    private int loopNumber;
    // 构造方法
    public WaitNotify(int flag, int loopNumber){
        this.flag = flag;
        this.loopNumber = loopNumber;
    }
    // 打印方法
    public void print(String info, int waitFlag, int nextFlag){
        for(int i=0;i<loopNumber;i++){
            synchronized (this){
                while(flag != waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(info);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}

2.await与notify实现
package com.learning.thread_order;

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

/**
 * @Author wangyouhui
 * @Description 线程交替执行
 **/
public class ThreadInTurnExecute2 {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);

        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();


        Thread thread1 = new Thread(()->{
            awaitSignal.print("线程1执行", a, b);
        });
        Thread thread2 = new Thread(()->{
            awaitSignal.print("线程2执行", b, c);
        });
        Thread thread3 = new Thread(()->{
            awaitSignal.print("线程3执行", c, a);
        });
        thread1.start();
        thread2.start();
        thread3.start();

        Thread.sleep(1000);
        awaitSignal.lock();
        try{
            System.out.println("开始");
            a.signal();
        }finally {
            awaitSignal.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock {
    private int loopNumber;

    public AwaitSignal(int loopNumber){
        this.loopNumber = loopNumber;
    }

    public void print(String info, Condition current, Condition next) {
        for(int i=0;i<loopNumber;i++){
            lock();
            try{
                current.await();
                System.out.println(info);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}
3.park与unpark实现
package com.learning.thread_order;

import java.util.concurrent.locks.LockSupport;

/**
 * @Author wangyouhui
 * @Description 线程交替执行
 **/
public class ThreadInTurnExecute3 {
    static Thread thread1;
    static Thread thread2;
    static Thread thread3;

    public static void main(String[] args) throws InterruptedException {
        ParkUnpark parkUnpark = new ParkUnpark(5);

        thread1 = new Thread(()->{
            parkUnpark.print("线程1执行", thread2);
        });
        thread2 = new Thread(()->{
            parkUnpark.print("线程2执行", thread3);
        });
        thread3 = new Thread(()->{
            parkUnpark.print("线程3执行", thread1);
        });
        thread1.start();
        thread2.start();
        thread3.start();

        LockSupport.unpark(thread1);
    }
}

class ParkUnpark {
    private int loopNumber;

    public ParkUnpark(int loopNumber){
        this.loopNumber = loopNumber;
    }

    public void print(String info, Thread next) {
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            System.out.println(info);
            LockSupport.unpark(next);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王佑辉

老板,赏点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值