- 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();
- }
- }
- }
复制代码 多个线程分别创建了锁实例后对同一对象加锁,不能实现同步的原因。具体解释一下。谢了
现在我有个疑问是:“多个线程分别创建了锁实例后对同一对象加锁”,与“jvm为每个对象都关联了唯一的一把锁”。二者好像矛盾? |