/**
* 买票案例,
* @author M-wise
*
*/
public class ThreadSync {
public static void main(String[] args) {
//3个线程
Ticket t = new Ticket();
Thread thread1 = new Thread(t,"窗口1");
Thread thread2 = new Thread(t,"窗口2");
Thread thread3 = new Thread(t,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
//票只有一份 所以要有线程安全
class Ticket implements Runnable{
Object object=new Object();
public int count = 50; //票数 总数
@Override
public void run() {
while(true){ //死循环
synchronized(object){
if(count>0){
count--;
System.out.println(Thread.currentThread().getName()
+"卖出了1张票,剩余票数:\t"+count);
}
else {
break;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}