【问题标题】:Why the same thread trying to lock the resource?为什么同一个线程试图锁定资源?
【发布时间】:2015-07-29 09:32:16
【问题描述】:

主类试图创建 4 个线程

运行线程后,每个线程都会尝试锁定。当一个线程获得锁时,其余的将等待解锁。 就我而言,一旦Thread 0 发现资源被锁定,然后Thread 0 进入等待状态,那为什么又Thread 0 试图锁定资源。

package com.test.thread;

public class LockImplementation {

    public static void main(String[] args) {

        MyNewThread myThread1 = new MyNewThread(1);
        MyNewThread myThread2 = new MyNewThread(2);
        MyNewThread myThread3 = new MyNewThread(3);
        MyNewThread myThread4 = new MyNewThread(3);

        myThread1.start();
        myThread2.start();
        myThread3.start();
        myThread4.start();              
    }               
}

class Lock {

    private boolean isLocked = false;
    private Thread lockingThread = null;
    int count = 0;

    public synchronized void lock() throws InterruptedException {
        if (isLocked) {
            System.out.println("trying to lock by thread " + 
            lockingThread.getName());
            wait();
        }
        System.out.println("Locked by thread " + 
        Thread.currentThread().getName());
        isLocked = true;
        lockingThread = Thread.currentThread();
    }

    public synchronized void unLock() {
        if (this.lockingThread != Thread.currentThread()) {
            throw new IllegalMonitorStateException("Calling thread has not locked this lock");
        }
        isLocked = false;
        lockingThread = null;
        notify();
    }
}

class MyNewThread extends Thread {

    int thNo;
    private static Lock lock;

    public MyNewThread(int thNo) {
        Thread.currentThread().setName(thNo + "");
        this.thNo = thNo;
        lock = new Lock();
    }

    @Override
    public void run() {
        System.out.println("start running thread no " + 
        Thread.currentThread().getName());
        try {
            lock.lock();
            Thread.sleep(10000);
            lock.unLock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end running thread no " + 
        Thread.currentThread().getName());
    }               
}

为什么同一个线程试图锁定资源?

【问题讨论】:

  • 你试过调试吗?
  • 您的程序有一个静态变量lock,但它创建了四个新的Lock 对象,并为该变量分配了四次。那可能是不对的。
  • 你的if 测试应该是while 测试。

标签: java multithreading


【解决方案1】:

发生这种情况是因为当您第一次进入 lock 方法时,您将锁定线程设置为第一个进入它的线程。调用 lock() 时的下一个线程看到 isLocked 为 true 并等待,但锁定线程仍然相同并且不会更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2015-08-23
    相关资源
    最近更新 更多