java多线程(wait notify)

该博客讨论了如何在Java中使用多线程实现交替售票的场景。通过创建两个线程类`Test1`和`Test2`,分别模拟两个售票窗口,使用`synchronized`关键字保证线程安全,确保每个窗口轮流售票。代码中使用`wait()`和`notify()`方法进行线程间的同步。当票数为0时,所有线程被唤醒,程序结束。
摘要由CSDN通过智能技术生成

java 多线程交替执行

今天我们来聊点多线程的内容。先举个例子,假如有两个售票窗口,但是只有10张票,只能卖给10个人,不能超卖,且要求,1窗口卖一张,2窗口卖下一张,交替售票,这个场景咋玩下。以下是自己的一些思路,请各位大神说说看法
package com.example.feignclient.process;

/**
 * @author : feng
 * @date : 2022/4/11 16:13
 * @desc :
 */
public class Test1 extends Thread {

    private Test test;

    public Test1(Test test) {
        this.test = test;
    }

    @Override
    public void run() {
        while (test.ticket > 0) {
            synchronized (test) {
                try {
                    if (test.ticket > 0) {
                        test.ticket = test.ticket - 1;
                        System.out.println(Thread.currentThread().getName() + "车票:" + test.ticket);

                    }
                    test.notify();
                    test.wait();
                    // Thread.sleep(1000L);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (test.ticket == 0) {
                    test.notifyAll();
                }
            }


        }
    }
}

package com.example.feignclient.process;

/**
 * @author : feng
 * @date : 2022/4/11 16:13
 * @desc :
 */
public class Test2 extends Thread {

    private Test test;

    public Test2(Test test) {
        this.test = test;
    }

    @Override
    public void run() {
        while (test.ticket > 0) {
            synchronized (test) {
                try {
                    if (test.ticket > 0) {
                        test.ticket = test.ticket - 1;
                        System.out.println(Thread.currentThread().getName() + "车票:" + test.ticket);
                    }
                    test.notify();
                    test.wait();
                    // Thread.sleep(1000L);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (test.ticket == 0) {
                    test.notifyAll();
                }
            }

        }
    }
}
package com.example.feignclient.process;

/**
 * @author : feng
 * @date : 2022/4/11 16:14
 * @desc :
 */
public class Test {
   public int ticket = 10;
    public static void main(String[] args)throws Exception {

        Test test = new Test();
        Test1 t1 = new Test1(test);
        Test2 t2 = new Test2(test);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(test.ticket);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值