写一个多线程卖票的程序
public class SaleTickets {
public static void main(String[] args) {
T t = new T();
for (int i = 0; i < 10; i++) {
new Thread(t).start();
}
}
}
class T implements Runnable{
private static int tickets = 100;
@Override
public void run() {
while (true){
synchronized (this){
if (tickets >= 1){
System.out.println(Thread.currentThread().getName() + " 正在售卖第 " + tickets + " 张票 ");
tickets--;
} else {
System.out.println(Thread.currentThread().getName() + " 票已经卖完");
break;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|