Java 如何为信号量中等待的线程赋予优先级?
我使用了一个信号量来限制访问函数的线程数。我希望下一个被唤醒的线程应该按照我将给出的优先级来选择,而不是默认的信号量唤醒线程的方式?我们如何才能做到这一点 以下是实施方案:Java 如何为信号量中等待的线程赋予优先级?,java,multithreading,semaphore,java-threads,blockingqueue,Java,Multithreading,Semaphore,Java Threads,Blockingqueue,我使用了一个信号量来限制访问函数的线程数。我希望下一个被唤醒的线程应该按照我将给出的优先级来选择,而不是默认的信号量唤醒线程的方式?我们如何才能做到这一点 以下是实施方案: class MyMathUtil2 implements Runnable { double a; double b; String name = "demo"; Thread t; //static int currentCount = 0; static int MAX_C
class MyMathUtil2 implements Runnable {
double a;
double b;
String name = "demo";
Thread t;
//static int currentCount = 0;
static int MAX_COUNT = 2;
private final Semaphore available = new Semaphore(MAX_COUNT, true);
MyMathUtil2(double v1, double v2) {
a = v1;
b = v2;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void InternalPow(double a, double b) throws InterruptedException {
available.acquire();
try {
System.out.println("Power of " + a + " and " + b + " : " + Math.pow(a, b));
} finally {
available.release();
}
}
public void run() {
try {
InternalPow(a, b);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class TestMyMathUtil2 {
public static void main(String args[]) {
new MyMathUtil2(10.2, 8);
new MyMathUtil2(11, 56);
new MyMathUtil2(10.2, 9);
new MyMathUtil2(2, 3);
new MyMathUtil2(4, 5);
}
}
嗯,
信号量不支持优先级
我建议使用a with2
固定线程和a来解决此问题
带有2
固定线程的ThreadPoolExecutor
可以确保在任何时刻,最多运行2
任务。其他任务将放在此优先级BlockingQueue
中,线程池将根据自定义设置从队列中检索任务
这里有一个例子。本例中的每个Runnable
都应该打印一个数字。它以相反的顺序提交Runnable
s:1000999,…,1。
但是Runnable
将按自然顺序执行:1、2、…、1000使用优先级队列
import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class ComparableRunnable implements Runnable {
public int index;
ComparableRunnable(int index) {
this.index = index;
}
public void run() {
System.out.println(Thread.currentThread().getName() + "-index : " + index);
try {
// sleep current thread, so the other thread can print
// this is not mandatory, without this, the result might not follow strict natural order
// for example, thread1 print 1,
// thread2 take 2 but did not print it immediatly,
// thread1 print 3,
// thread2 print 2
// the result will be 1, 3, 2,
Thread.sleep(10);
} catch (Exception e) {
}
}
public static void main(String[] args) {
int corePoolSize = 2; // fixed thread number
long ignore = 0L;
// comparator
Comparator<Runnable> comparator = new Comparator<Runnable>() {
@Override
public int compare(Runnable o1, Runnable o2) {
int index1 = ((ComparableRunnable)o1).index;
int index2 = ((ComparableRunnable)o2).index;
// you should implement this method based on your own order
return Integer.compare(index1, index2);
}
};
// use the comparator create a priority queue
PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<>(10, comparator);
ThreadPoolExecutor executor =
new ThreadPoolExecutor(corePoolSize, corePoolSize, ignore, TimeUnit.SECONDS, queue);
// Warm the thread pool up
// this is not mandatory, without this, it will print 1000, 999, 1, 2, ...., 998
// because the first two Runnbale will be executed once they are submitted
for (int i = 0; i < corePoolSize; i++) {
executor.execute(() -> {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
});
}
// submit in 1000, 999, ..., 1 order
// print in 1, 2, 3, ..., 1000 order
for (int i = 1000; i > 0; i--) {
executor.execute(new ComparableRunnable(i));
}
}
}
公平性参数(上面的true)确保线程按到达顺序唤醒,但据我所知,没有内置类可以按优先级顺序唤醒线程。您必须对信号量进行子类化,或者使用其他更基本的原语,然后自己完成。检查信号量的来源,因为它支持顺序,它应该非常接近您需要的。您不想使用有界的PriorityBlockingQueue
?@Andrew..我没有任何使用PriorityBlockingQueue的经验。如果你以前使用过它,请相应地修改代码并与我们分享…wud b真的很有用。你能后退一步让我们理解你为什么要这样做吗。为什么你需要这个优先顺序。现在你正在询问实施的细节。嗨@Gray,很高兴你这么问。这实际上是一家知名网络公司向我提出的面试问题的一部分。如果你在这方面想得更多,你会意识到这是有道理的,因为每次都可能不是a/c到FCFS规则。如果你有n个sms线程在线程池中等待,并且它们有类型,你肯定会希望包含SMSE的OTP在正常SMSE之前得到服务。这似乎很有希望,所以接受它作为答案。谢谢
pool-1-thread-1-index : 1
pool-1-thread-2-index : 2
pool-1-thread-1-index : 3
pool-1-thread-2-index : 4
pool-1-thread-2-index : 5
...
pool-1-thread-2-index : 996
pool-1-thread-2-index : 997
pool-1-thread-1-index : 998
pool-1-thread-2-index : 999
pool-1-thread-1-index : 1000