package com.itheima02;
public class Demo01_Ticket {
public static void main(String[] args) {
Demo02_Runnable dr = new Demo02_Runnable();
Thread th = new Thread(dr);
Thread th1 = new Thread(dr);
Thread th2 = new Thread(dr);
th.start();
th1.start();
th2.start();
}
}
package com.itheima02;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo02_Runnable implements Runnable {
static int tickets = 100;
Lock lock = new ReentrantLock();
private Object obj = new Object();
@Override
public void run() {
while(true) {
synchronized (obj) {
//lock.lock();
if(tickets > 0) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
String s = Thread.currentThread().getName();
System.out.println(s + "正在售:第"+tickets--+"张票");
}else {
break;
}
}
//lock.unlock();
}
}
}
|
|