ThreadDemo4

package com.shrimpking.t1;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/9/21 16:57
 */
class TestThread4 extends Thread{
    private int tickets = 5;

    @Override
    public void run(){
        while (tickets > 0){
            System.out.println(Thread.currentThread().getName() +"出票" + tickets);
            tickets -= 1;
        }
    }
}

//ch15-4 多线程模拟售票
public class ThreadDemo4
{
    public static void main(String[] args)
    {
        TestThread4 th = new TestThread4();

        th.start();
        th.start();
        th.start();
        th.start();

    }
}

好的,我可以帮你回答这个问题。 首先,我们需要定义一个共享资源,即200张票的数量,这个数量需要被4个线程同时访问和修改,因此需要使用synchronized函数来保证线程安全。 下面是一个简单的Java代码实现: ``` public class TicketSystem { private static int ticketNum = 200; public synchronized static boolean buyTicket(int num) { if (ticketNum >= num) { ticketNum -= num; System.out.println("成功购买" + num + "张票,剩余票数:" + ticketNum); return true; } else { System.out.println("购买" + num + "张票失败,剩余票数:" + ticketNum); return false; } } } public class ThreadDemo extends Thread { private int ticketNum; public ThreadDemo(int ticketNum) { this.ticketNum = ticketNum; } public void run() { try { sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } TicketSystem.buyTicket(ticketNum); } } public class Main { public static void main(String[] args) { ThreadDemo t1 = new ThreadDemo(50); ThreadDemo t2 = new ThreadDemo(50); ThreadDemo t3 = new ThreadDemo(50); ThreadDemo t4 = new ThreadDemo(50); t1.start(); t2.start(); t3.start(); t4.start(); } } ``` 在这个代码中,TicketSystem类定义了一个共享资源ticketNum,并使用synchronized函数来保证线程安全。buyTicket函数用于购买票,每次购买需要传入购买的数量num,如果剩余票数足够,则减去相应数量的票,并返回true,否则返回false。 ThreadDemo类继承自Thread类,重写了run函数,在run函数中调用TicketSystem的buyTicket函数来购买票。 Main类创建了4个ThreadDemo实例,分别购买50张票。 在执行这个程序时,由于synchronized函数的保证,4个线程将会按顺序访问和修改ticketNum的值,从而保证线程安全。同时,sleep(5)函数模拟了网络传输延时,这也是实际情况中需要考虑的因素。 希望这个代码能够帮助你理解synchronized函数的使用和线程安全的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

虾米大王

有你的支持,我会更有动力

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

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

打赏作者

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

抵扣说明:

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

余额充值