class Ticket implements Runnable//extends Thread
{
private int num = 100;
Object obj = new Object();//这个对象锁放在里面和放在外面有什么区别 ,没怎么听清楚,求解释。。
public void run()
{
//Object obj = new Object();
while(true)
{
synchronized(obj)
{
if(num>0)
{
try{Thread.sleep(10);}catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....sale...."+num--);
}
}
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();//创建一个线程任务对象。
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
/*
Ticket t1 = new Ticket();
// Ticket t2 = new Ticket();
// Ticket t3 = new Ticket();
// Ticket t4 = new Ticket();
t1.start();
t1.start();//一个线程不能开启两次,会抛出无效线程状态异常
t1.start();
t1.start();
*/
}
} |
|