//票池
class TickPool{
private int tickets = 100 ;
//同步方法.使用的当前对象作为锁旗标 -- this
public synchronized int getTicket(){
if(tickets <= 0){
return 0 ;
}
int tmp = tickets ;
tickets = tickets - 1 ;
return tmp ;
}
}
//售票员
class Saler extends Thread{
TickPool pool ;
String name ;
public Saler(String name,TickPool pool){
this.pool = pool ;
this.name = name ;
}
public void run(){
while(true){
int no = pool.getTicket();
if(no != 0){
System.out.println(name + " : " + no);
}
else{
return ;
}
}
}
}
class ThreadDemo7{
public static void main(String[] args){
TickPool pool = new TickPool();
Saler s1 = new Saler("No1",pool);
Saler s2 = new Saler("No2",pool);
Saler s3 = new Saler("No3",pool);
//
s1.start();
s2.start();
s3.start();
}
}
class TickPool{
private int tickets = 100 ;
//同步方法.使用的当前对象作为锁旗标 -- this
public synchronized int getTicket(){
if(tickets <= 0){
return 0 ;
}
int tmp = tickets ;
tickets = tickets - 1 ;
return tmp ;
}
}
//售票员
class Saler extends Thread{
TickPool pool ;
String name ;
public Saler(String name,TickPool pool){
this.pool = pool ;
this.name = name ;
}
public void run(){
while(true){
int no = pool.getTicket();
if(no != 0){
System.out.println(name + " : " + no);
}
else{
return ;
}
}
}
}
class ThreadDemo7{
public static void main(String[] args){
TickPool pool = new TickPool();
Saler s1 = new Saler("No1",pool);
Saler s2 = new Saler("No2",pool);
Saler s3 = new Saler("No3",pool);
//
s1.start();
s2.start();
s3.start();
}
}