public class MyRunnable implements Runnable {
private int tickets=100;
private Object obj=new Object ();
@Override
public void run() {
while (true){
synchronized (obj){
if(tickets>0){
try {
Thread.sleep (100);
} catch (InterruptedException e) {
e.printStackTrace ( );
}
System.out.println (Thread.currentThread ().getName ()+":正在买第"+tickets-- +"张票");
}
}
}
}
}
public class TicketTest {
public static void main(String[] args) {
MyRunnable res =new MyRunnable ();
Thread windows1 =new Thread ( res );
Thread windows2 =new Thread ( res );
Thread windows3 =new Thread ( res );
windows1.setName ("窗口1");
windows2.setName ("窗口2");
windows3.setName ("窗口3");
windows1.start ();
windows2.start ();
windows3.start ();
}
}