/**
* 买票问题
*/
public class ThreadTrain1 implements Runnable {
private int count = 10;
private static Object o = new Object();
@Override
public void run() {
while (count>0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sale();
}
}
private void sale() {
// 前提 多线程进行使用、多个线程只能拿到一把锁。
// 保证只能让一个线程 在执行 缺点效率降低
synchronized (o){
if (count>0){
System.out.println(Thread.currentThread().getName()+",出售第"+(10-count+1)+"张票");
count--;
}
}
}
public static void main(String[] args){
ThreadTrain1 train1 = new ThreadTrain1();
Thread t1 = new Thread(train1,"1号窗口");
Thread t2 = new Thread(train1,"2号窗口");
t1.start();
t2.start();
}
}
原文地址:https://www.cnblogs.com/fly-book/p/11439328.html
时间: 2024-10-01 10:04:03