求指教如何唤醒wait方法下的特定线程
Java中似乎没有提供唤醒特定线程的方法,无论是notify函数还是notifyall()函数,这里如果想按照特定顺序唤醒线程,或者唤醒特定线程的话,请问有什么方法没?
最好能举个代码例子吧,谢谢了!
[解决办法]
http://bbs.csdn.net/topics/50035854
[解决办法]
用wait、notify是可以解决的啊。你可以每个线程定义一个锁对象。
[解决办法]
使用ReentrantLock配合多个condition来达到唤醒指定线程的目的,将唤醒目标 condition 与thread 做关联,建立联系,找到thread的instance就可以找到thread的监视对象condition.
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class NotifySpecfiedThread {
private static final Map<Thread, Condition> notifyRelationship = new ConcurrentHashMap<Thread, Condition>();
private static final ReentrantLock locker = new ReentrantLock(false);
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
final int waitThreadNumber = 10;
for (int i = 1; i <= waitThreadNumber; i++) {
final Thread t = new WaitThreadTest();
notifyRelationship.put(t, locker.newCondition());
}
final Set<Thread> threads = notifyRelationship.keySet();
for (final Thread t : threads) {
t.start();
}
new NotifyThreadTest().join();
}
static class WaitThreadTest extends Thread {
public WaitThreadTest() {
}
/**
* notify the specified thread using different condition and lock with
* the same ReentrantLock instance
*/
public void run() {
locker.lock();
try {
final Thread t = Thread.currentThread();
final ThreadLocal<Boolean> isWait = new ThreadLocal<Boolean>();
isWait.set(true);
while (isWait.get()) {
try {
System.out.println("i am ready to wait,"
+ " the thread name is:" + t.getName());
final Condition c = notifyRelationship.get(this);
c.await();
isWait.set(false);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
}
}
System.out.println("i have been released, the thread name is:"
+ t.getName());
} finally {
locker.unlock();
}
}
}
/**
* loop all the condition instance and release the wait thread..
*/
static class NotifyThreadTest extends Thread {
public NotifyThreadTest() {
this.start();
}
public void run() {
final Set<Entry<Thread, Condition>> entrySet = notifyRelationship
.entrySet();
for (final Entry<Thread, Condition> entry : entrySet) {
final Thread t = entry.getKey();
final Condition c = entry.getValue();
System.out.println("i am ready to signal, "
+ "will be signaled thread name is:" + t.getName());
locker.lock();
try {
c.signal();
} finally {
locker.unlock();
}
System.out.println("i have alreay signaled the specified "
+ "thread:" + t.getName());
}
}
}
}
