java多线程实现火车售票系统 以及java中的同步的实现 同步块 和同步方法同时 同步...

/*
利用Java 多线程模拟火车站售票系统 了解java中的同步


class Test
{
public static void main(String []args)
{
SellThread st=new SellThread(); //创建一个实现了implements接口的对象
new Thread(st).start(); //启动四个Thread
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}

class SellThread implements Runnable
{
int index =100;
public void run()
{
while(true)
{
if(index>0)
{
try
{
Thread.sleep(10); //函数抛出异常我们要进行异常捕获 休眠之后 所有Thread等待在这里
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"sell tickets "+ index--);
}
}
}

}


*/

/*

上面的代码 不能保证同步 即每次只允许一个 THREAD访问 资源 我们要对这个临界区进行保护
每个对象都有一个监视器 通过检测对象是否被枷锁 从而判断是否进入临界区
同步快监视的是任意 对象 而同步方法监视的是 this 对象

有2种方法 1.同步块 2.同步方法
1. synchronized( Object)
{
......

}
2.方法前面加上 synchronized修饰

class Test
{
public static void main(String []args)
{
SellThread st=new SellThread(); //创建一个实现了implements接口的对象
new Thread(st).start(); //启动四个Thread
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}

class SellThread implements Runnable
{
int index =100;


*/
///同步块
/*public void run()
{
while(true)
{
synchronized(this) //通过对象监视器枷锁每次只有一个线程进入临界区这个监视对象可以是任意
{
if(index>0)
{
System.out.println(Thread.currentThread().getName()+"sell tickets "+ index--);
}
}
}
}
//同步块
public void run()
{
while(true)
{

sell(); //调用同步方法进行控制
}
}

/同步方法
synchronized public void sell()
{
if(index>0)
{
System.out.println(Thread.currentThread().getName()+"sell tickets "+ index--);
}
}

///同步方法

}


*/

///同步快与同步方法实现同步


class Test
{
public static void main(String []args) throws Exception
{
SellThread st=new SellThread(); //创建一个实现了implements接口的对象
new Thread(st).start(); //启动四个Thread
Thread.sleep(1);
st.b=true ; //
new Thread(st).start();
}
}

class SellThread implements Runnable
{
int index =100;
boolean b=false; //用来实现同步
Object o=new Object(); //获得一个检测对象

///同步块
public void run()
{
if(b==false)
{
while(true)
{
synchronized(o) //同步块可以监视任意对象但是 同步方法只能监视this 对象
{
if(index>0)
System.out.println("this "+Thread.currentThread().getName()+"sell ticket "+index--);
}
}
}
else
{
while(true)
if(index>0)
{
sell();
}
}
}
/同步方法
synchronized public void sell()
{
if(index>0)
{
System.out.println("this2 " +Thread.currentThread().getName()+"sell tickets "+ index--);
}
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值