多线程—“抢红包“的活动多线程模拟

家庭聚会组织了"抢红包"的活动,现在某家庭成员打算发3个定额红包[3个20元红包],现由5个家庭成员进行快抢,请使用多线程模拟该活动!实现效果

多线程—“抢红包“的活动多线程模拟_第1张图片

 

public class CO01 {
    /**
     * ↓ Please give him a name : ↓
     * @BooName:   抢红包
     * @Author:    Minds丶南弑
     * @Date:       2023/01/29--19:12
     */
    public static void main(String[] args) {
        RedWarsRunnable redWarsRunnable = new RedWarsRunnable() ;

        // 创建5个Thread对象,把第一步创建的对象作为Thread的构造方法参数传递过来
        Thread t1 = new Thread(redWarsRunnable , "黄蓉") ;
        Thread t2 = new Thread(redWarsRunnable , "郭靖") ;
        Thread t3 = new Thread(redWarsRunnable , "黄药师") ;
        Thread t4 = new Thread(redWarsRunnable , "周伯通") ;
        Thread t5 = new Thread(redWarsRunnable , "瑛姑") ;
        // 启动5个线程
        System.out.println("开始抢红包了!~~(*^▽^*)");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}
class RedWarsRunnable implements Runnable {
    //设置红包总数
    private int redWarsCount = 3;

    @Override
    public void run() {
        while (true) {

            synchronized (this) {
                if (redWarsCount <= 0) {
                    System.out.println(Thread.currentThread().getName() + "说:抽没了奥你们这群... ...");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "抽到了一个大红包" );
                //红包数量-1
                redWarsCount--;
                //保证一人只能抢一次
                break;
            }
        }
    }
}

你可能感兴趣的:(练习题目,java,intellij,idea)