`
txf2004
  • 浏览: 6867360 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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--);
}
}


}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics