售票类:
package duoxiancheng;
import java.util.concurrent.TimeUnit;
public class Ticket implements Runnable {
private int num = 100;
public Ticket() {
}
public Ticket(int num) {
this.num = num;
}
public void run() {
while (true) {
synchronized (this) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
if (num > 0) {
System.out.printf("[%s] 售出一张票,剩余%d张票%n", Thread.currentThread().getName(), --num);
} else {
System.out.printf("%n[%s] 票已售完,停止售票。", Thread.currentThread().getName());
break;
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
测试类:
package duoxiancheng;
public class Test4 {
public static void main(String[] args) {
Ticket ticket = new Ticket(20);
Thread thread = new Thread(ticket, "郑州站");
Thread thread1 = new Thread(ticket, "郑州东站");
Thread thread2 = new Thread(ticket, "郑州南站");
Thread thread3 = new Thread(ticket, "郑州北站");
thread.start();
thread1.start();
thread2.start();
thread3.start();
}
}
|