package test;
public class ThreadTest2 {
public static void main(String[] args) {
MyThread t = new MyThread();
new Thread(t,"卖票员A").start();
new Thread(t,"卖票员B").start();
new Thread(t,"卖票员C").start();
}
}
class MyThread implements Runnable{
private int ticket = 6;
@Override
public void run() {
for(int x=0;x<50;x++){
synchronized(this){//线程同步
if(this.ticket>0){//票数必须大于0才可以卖票
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票,ticket="+this.ticket--);
}
}
}
}
}
运行结果: