我正在使用应用程序逻辑线程和数据库访问线程创建Java应用程序.他们都坚持为应用程序的整个生命周期,并都需要在同一时间运行(一个会谈到服务器,一个谈判给用户;当应用程序完全启动,我需要两个人工作).
但是,在启动时,我需要确保最初应用程序线程等待直到db线程准备就绪(当前通过轮询自定义方法确定dbthread.isReady()).我不介意app线程阻塞,直到db线程准备好.
Thread.join() 看起来不像解决方案 - 数据库线程仅在应用程序关闭时退出.
while (!dbthread.isReady()) {} 有点工作,但空循环消耗了大量的处理器周期.
还有其他想法吗?谢谢.
Java中是否有一个库可以执行以下操作?A thread应重复sleepx毫秒,直到条件变为真或达到最大时间.
当测试等待某些条件变为真时,这种情况通常发生.这种情况受到另一个人的影响thread.
[编辑]为了使它更清楚,我希望测试在失败前只等待X ms.它不能永远等待条件成为现实.我正在添加一个人为的例子.
class StateHolder{
boolean active = false;
StateHolder(){
new Thread(new Runnable(){
public void run(){
active = true;
}
}, "State-Changer").start()
}
boolean isActive(){
return active;
}
}
class StateHolderTest{
@Test
public void shouldTurnActive(){
StateHolder holder = new StateHolder();
assertTrue(holder.isActive); // i want this call not to fail
}
}
Run Code Online (Sandbox Code Playgroud) 如何等待x秒或直到条件变为真?应该在等待时定期测试这种情况.目前我正在使用此代码,但应该有一个简短的功能.
for (int i = 10; i > 0 && !condition(); i--) {
Thread.sleep(1000);
}
Run Code Online (Sandbox Code Playgroud) 我有一个 Manager 类,多个线程向其中注册自己(用于为UUID每个请求生成唯一标识符),提供要处理的有效负载并从管理器获取相应的响应。我用来java.util.concurrent.ExecutorService启动多个线程。这是测试我的管理器功能的实现 -
public class ManagerTest {
public static void main(String[] args) {
try {
Manager myManager = new Manager();
// Start listening to the messages from different threads
myManager.consumeMessages();
int num_threads = Integer.parseInt(args[0]);
ExecutorService executor = Executors.newFixedThreadPool(num_threads);
for (int i = 0; i < num_threads; i++) {
// class implementation is given below
Runnable worker = new MyRunnable(myManager);
executor.execute(worker);
}
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println("\nFinished all …Run Code Online (Sandbox Code Playgroud) java concurrency multithreading java.util.concurrent java-threads