hasQueuedThread()、hasQueuedThreads()、hasWaiters()方法的使用

/ 多线程 / 没有评论 / 292浏览

hasQueuedThread():查询指定的线程是否正在等待获取锁。

hasQueuedThreads():查询是否有线程正在等待获取锁。

hasWaiters():查询是否与指定Condition类有关的等待线程。

下面我们看具体的代码。

/**
* 用户登录
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:35
* @since 1.0.0
*/
public class Userinfo {

public ReentrantLock lock = new ReentrantLock();

public void test() {
try {
lock.lock();
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
/**
* 管理用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestAdmin extends Thread {

private Userinfo userinfo;


public RequestAdmin(Userinfo userinfo) {
this.userinfo = userinfo;
}

@Override
public void run() {
userinfo.test();
}
}
/**
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-20 13:35
* @since 1.0.0
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
Userinfo userinfo = new Userinfo();
RequestAdmin requestAdmin = new RequestAdmin(userinfo);
RequestAdmin requestAdmin2 = new RequestAdmin(userinfo);
requestAdmin.start();
Thread.sleep(1000);
requestAdmin2.start();
Thread.sleep(1000);
System.out.println(userinfo.lock.hasQueuedThread(requestAdmin));
System.out.println(userinfo.lock.hasQueuedThread(requestAdmin2));
System.out.println(userinfo.lock.hasQueuedThreads());
}
}
false
true
true

下面我们看一下hasWaiters()方法的例子。

/**
* 用户登录
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:35
* @since 1.0.0
*/
public class Userinfo {

public ReentrantLock lock = new ReentrantLock();

private Condition condition = lock.newCondition();

public void await() {
try {
lock.lock();
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void signal() {
lock.lock();
System.out.println(String.format("是否有线程在等待condition锁:%s\t等待的线程数是多少:%s\tthread: %s", lock.hasWaiters(condition), lock.getWaitQueueLength(condition), Thread.currentThread().getName()));
condition.signal();
lock.unlock();
}

}
/**
* 管理用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestAdmin extends Thread {

private Userinfo userinfo;


public RequestAdmin(Userinfo userinfo) {
this.userinfo = userinfo;
}

@Override
public void run() {
userinfo.await();
}
}
/**
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-20 13:35
* @since 1.0.0
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
Userinfo userinfo = new Userinfo();
RequestAdmin[] requestAdmins = new RequestAdmin[10];
for (int i = 0; i < requestAdmins.length; i++) {
requestAdmins[i] = new RequestAdmin(userinfo);
}
for (int i = 0; i < requestAdmins.length; i++) {
requestAdmins[i].start();
}
Thread.sleep(1000);
userinfo.signal();
}
}
是否有线程在等待condition锁:true	等待的线程数是多少:10	thread: main