package com.tools;
/**
* 同步方法处理多线程共用资源的问题
* @author Administrator
*
*/
class TicketSouce implements Runnable
{
//票的总数
private int ticket=99;
public void run()
{
for(int i=1;i<200;i++)//时间
{
try {
//休眠1秒中,为了使效果更明显,否则可能出不了效果
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sale();
}
}
public synchronized void sale()
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket--+"号票");
}
}
}
public class Test {
public static void main(String args[])
{
TicketSouce mt=new TicketSouce();
//基于火车票创建10个窗口
new Thread(mt,"a").start();
new Thread(mt,"b").start();
new Thread(mt,"c").start();
new Thread(mt,"d").start();
new Thread(mt,"e").start();
new Thread(mt,"f").start();
new Thread(mt,"g").start();
new Thread(mt,"h").start();
new Thread(mt,"i").start();
new Thread(mt,"j").start();
}
}
多线程数据同步之synchronized同步方法-多线程访问临界资源
最新推荐文章于 2023-02-19 07:15:13 发布