[Java] 纯文本查看 复制代码
public class Test2 {
public static void main(String[] args) {
P p_tingchce = new P();//创建对象
//开启两个线程模拟两个入口
new Thread(p_tingchce,"第一个入口").start();
new Thread(p_tingchce,"第二个入口").start();
}
}
class P implements Runnable{
int p_st=100;
//设定100个停车位
Object o=new Object();//定义一个对象 用于同步代码块的锁
@Override
public void run() {
//同步锁
synchronized (o) {
while(true){
if (p_st>0) {
//打印车位号
System.out.println(Thread.currentThread().getName()+" "+p_st--);
try {
Thread.sleep(100);
//模拟耗时100毫秒
} catch (InterruptedException e) {
}
}else {
//停满后终止
break;
}
}
}
}
}