package sell_ticket;
public class ThreadTicket {
public static void main(String[] args) {
MyThread m = new MyThread();
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
Thread t3 = new Thread(m);
t1.start();
t2.start();
t3.start();
}
}
class MyThread implements Runnable{
private int ticket=100;
//synchronized
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//用synchronized包起来,形成同步代码块,但后来发现用不用其实一样
synchronized(this){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"出售了"+ticket);
ticket--;
}
}
}
}
}
以上还有另一个写法,synchronized一个方法:
class Test implements Runnable
{
//票的总数
private int ticket=20;
public void run()
{
//50只是用来循环,无意义
for(int i=1;i<50;i++)
{
try {
//休眠1s秒中,为了使效果更明显,否则可能出不了效果
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sale();
}
}
public synchronized void sale()
{
if(ticket>0)
{
//很有意思的一个发现,如果用System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket--+"号票"); 哪怕不用synchronized,重复卖票的现像也会低很多
System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket+"号票");
ticket--;
}
}
public static void main(String args[])
{
Test mt=new Test();
//基于火车票创建三个窗口
new Thread(mt,"a").start();
new Thread(mt,"b").start();
new Thread(mt,"c").start();
}
}
第二种,采用堆栈的方式: