class SaleTicke implements Runnable
{
int k=10; //注意这里不用静态,因为只创建一个Runable子类的对象
public void run()
{
while(true)
{
synchronized("锁")
{
if(k>0)
{
System.out.println(Thread.currentThread().getName()+"卖了第"+k+"张");
k--;
}
else
{
System.out.println("票卖完了");
break;
}
}
}
}
}
class wu
{
public static void main(String [] args)
{
SaleTicke st1 = new SaleTicke();
Thread th1 = new Thread(st1,"窗口一");
Thread th2 = new Thread(st1,"窗口二");
Thread th3 = new Thread(st1,"窗口三");
th1.start();
th2.start();
th3.start();
}
}14.3 线程的实现方式二练习:买票
最新推荐文章于 2024-08-29 19:39:30 发布
本文通过一个具体的多线程售票系统示例,展示了如何使用synchronized关键字确保线程安全,实现多个线程同步访问并修改共享资源,避免了竞态条件导致的数据不一致问题。
1118

被折叠的 条评论
为什么被折叠?



