package ThreadTest;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TicketTest {
public static void main(String[] args) {
TicketsThread tt = new TicketsThread();
Thread station1 = new Thread(tt, "售票点1");
Thread station2 = new Thread(tt, "售票点2");
Thread station3 = new Thread(tt, "售票点3");
station1.start();
station2.start();
station3.start();
}
}
class TicketsThread implements Runnable {
int tickets = 0;
public void run() {
Lock lock = new ReentrantLock();//注意在run方法中
while (true) {
lock.lock();
if (tickets < 100) {
tickets++;
System.out.println(Thread.currentThread().getName() + "售出第"
+ tickets + "张票");
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
}
}
}
//求没能实现同步的原因及关于多个线程分别创建了锁实例后对同一对象加锁的问题。