class Ticket implements Runnable
{
private int tick = 100; //卖100张票
//Object o = new Object();
boolean b = true;//标志位分流
public void run()//卖票的代码要被多个线程所执行,存在于run方法中
{
if(b)
while(true)//一直循环,无特殊意义
{
//synchronized(o)
synchronized(this)
{
if(tick>0)//不能卖出0号票
{
try {Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+"卖 :code"+tick--);
//注意实现的话不能直接调用currentThread
}
}
}
else
while(true)//一直循环,无特殊意义
show();//调用同步函数
}
synchronized void show() //同步函数的锁是this
{
if(tick>0)//不能卖出0号票
{
try {Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+"卖 :show........."+tick--);
//注意实现的话不能直接调用currentThread
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();//售票窗口
Thread t1 = new Thread(t); //传参
Thread t2 = new Thread(t);
t1.start(); //开启线程
try {Thread.sleep(10);} catch (Exception e) {}
t.b = false;
t2.start();
}
}