为什么同一个线程要锁定资源

时间:2015-07-29 09:32:16

标签: java multithreading

            ## The main class trying to create 4 threads ##
          **
  

块引用

因此在运行线程后,每个线程都尝试锁定,一个线程获得锁定,其余线程将等待解锁。 在我的情况下,一旦线程0发现资源被锁定,然后线程0进入等待状态,那么为什么线程0再次尝试锁定资源。 **                 包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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("end running thread no " + Thread.currentThread().getName());
                }

            };

1 个答案:

答案 0 :(得分:0)

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