如何解决JavaScala阻止队列是否可以允许队列跳线更高优先级?
一个人可以使用LinkedBlockingQueue
来阻止操作。假设我队列中只有1个元素,每个元素都可以使用它。
val q = new LinkedBlockingQueue() // 1 element in it
def fun() = {
val instance = q.take()
// do some operations
}
def foo() = {
val instance = q.take()
// do some operations
}
// Use 3 threads to run following 3 methods,and the order they call q.take() is following
fun()
fun() // will wait for first fun()
foo() // will wait for second fun()
这些方法完成的顺序为fun(),fun(),foo()
但是,现在我想将foo
设置为更高的优先级,这意味着允许它成为跳过队列的对象。 foo
可以在第二个fun()
之前实例化(在第二个fun
等待时,foo
跳到它的前面)
它们完成的顺序可能变为fun(),foo(),fun()
,(第一个fun
将使用该实例,因为该实例可用,第二个应该等待,然后foo
也要等待,但是跳到第二个fun
的前面
可以吗?还是有其他可能的数据结构
解决方法
我不知道该任务有任何内置工具,但是实现起来并不难。由于您只想交换一个元素,因此不需要队列,而只需一个交换器。
一个简单的实现可能看起来像
database:
name: yourdbname
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: ######
password: ######
url: jdbc:mysql://sql2.freemysqlhosting.net:3306/${database.name}&useSSL=false&createDatabaseIfNotExist=true
对于您的两个普通消费者和一个优先级消费者以及少量生产者,这可能已经足够。
对于更多线程,您可能希望使用class SingleElementExchanger<T> {
int priorityConsumer;
T value;
public synchronized void set(T newValue) throws InterruptedException {
Objects.requireNonNull(newValue);
while(value != null) wait();
value = newValue;
notifyAll();
}
public synchronized T ordinaryGet() throws InterruptedException {
while(priorityConsumer != 0 || value == null) wait();
T received = value;
value = null;
notifyAll();
return received;
}
public synchronized T priorityGet() throws InterruptedException {
priorityConsumer++;
try {
while(value == null) wait();
T received = value;
value = null;
notifyAll();
return received;
}
finally {
priorityConsumer--;
}
}
}
而不是使用Lock
来通知正确的参与者。
notifyAll()
,
您需要根据自己的需要查找CompletableFuture。这样您就可以实现任务排序。
CompletableFuture<String> text = CompletableFuture.supplyAsync(() -> {
return "";
}).thenApply(param -> {
return "";
}).thenApply(param -> {
return "";
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。