package duoxiancheng;
class Ticket1 implements Runnable
{
private static int ticket=100;
public void run()
{
while(true)//执行100循环
{
show();
}
}
public static synchronized void show()//同步函数,其锁是this若该函数被静态修饰则其锁是类名.class
{
if(ticket>0)
System.out.println(Thread.currentThread().getName()+" "+ticket--);
}
}
public class ThreadTicketDemo1 {
public static void main(String[] args) {
Ticket1 t=new Ticket1();
Thread d1=new Thread(t);
Thread d2=new Thread(t);
d1.start();
d2.start();
}
}
(多线程)ThreadTicketDemo1
最新推荐文章于 2022-04-25 22:50:34 发布
本文展示了一个使用Java实现的多线程售票程序案例。通过一个静态同步方法控制并发访问,确保了在多个线程同时运行的情况下票数的正确递减。此程序有助于理解Java中线程同步的基本概念。
4万+

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



