- public class Ticket implements Runnable{
-
- //定义车上总共的座位数量
- int x = 70;
- Object lock = new Object();
-
- @Override
- public void run() {
- while (true) {
- //上锁
- synchronized (lock) {
- if (x>=0) {
- System.out.println("从"+Thread.currentThread().getName()+"上车,还有"+(x--)+"个座位。");
- }
- }
- }
- }
- }
- public class Test02 {
- public static void main(String[] args) {
- // 创建票对象
- Ticket t = new Ticket();
-
- //实例化上车的两个门[双线程]
- Thread t1 = new Thread(t,"前门");
- Thread t2 = new Thread(t,"后门");
-
- //开启线程
- t1.start();
- t2.start();
- }
- }
复制代码 |