相关疑难解决方法(0)

如何让Java线程等待另一个线程的输出?

我正在使用应用程序逻辑线程和数据库访问线程创建Java应用程序.他们都坚持为应用程序的整个生命周期,并都需要在同一时间运行(一个会谈到服务器,一个谈判给用户;当应用程序完全启动,我需要两个人工作).

但是,在启动时,我需要确保最初应用程序线程等待直到db线程准备就绪(当前通过轮询自定义方法确定dbthread.isReady()).我不介意app线程阻塞,直到db线程准备好.

Thread.join() 看起来不像解决方案 - 数据库线程仅在应用程序关闭时退出.

while (!dbthread.isReady()) {} 有点工作,但空循环消耗了大量的处理器周期.

还有其他想法吗?谢谢.

java multithreading

125
推荐指数
7
解决办法
26万
查看次数

Java定时器线程操作

我正在使用计时器线程来运行简单的打印功能。问题是,如果我将延迟时间设置为 1000 毫秒,程序就会直接退出,没有任何输出。

但如果我改成100ms,程序就可以了。

public class TimerTaskTest01 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new MyTask(), 1000);
    }
}
class MyTask extends TimerTask {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Hello World... ");
        }
        System.out.println("END");
    }
}
Run Code Online (Sandbox Code Playgroud)

我想也许主线程运行得太快了。但有没有人能告诉我,我的说法是对还是错……

java

5
推荐指数
1
解决办法
1181
查看次数

为什么我的`main()`在junit测试中没有捕获`timer`中抛出的异常?

这是我的主要方法:

public static void main(String... args) throws ClassNotFoundException {
    String[] classAndMethod = args[0].split("#");
    if (helpCmd(args)) {
        printHelpForTest(classAndMethod[1]);
        System.exit(0);
    }

    Result result = runTest(classAndMethod);
    exitIfTimeOutExceptionThrown(result);
    System.exit(result.wasSuccessful() ? 0 : 1);
}

private static void exitIfTimeOutExceptionThrown(Result result) {
    boolean isTimeOut = Iterables.filter(result.getFailures(), CodeBlockTimeOutException.class).iterator().hasNext();
    if (isTimeOut)
    {
        System.exit(2);
    }
}
Run Code Online (Sandbox Code Playgroud)

运行此junit测试:

    @Test
    public void sendSearchRequest() throws Exception {

...

        setTimeOut();

...
    }

private void setTimeOut() {
    if (criticalBlockTimeOut != null) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                throw …
Run Code Online (Sandbox Code Playgroud)

java junit exception error-code runtimeexception

1
推荐指数
1
解决办法
100
查看次数