【发布时间】: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