【发布时间】:2021-11-02 23:46:56
【问题描述】:
主线程(RunnableTest)不应等待其他线程(RunnableExample)执行循环以打印从0到4的数字。主线程和其他线程将并行执行。再次接收到从其他线程返回的结果后,主线程将处于动作模式。我怎样才能做到这一点?
我有一个主线程,如下所示:
public class RunnableTest {
public static void main(String[] args) {
//some code
new RunnableExample();
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Upon receiving result from RunnableExample thread again main thread will be in action and perform some task
}
}
另一个执行特定任务的线程:
public class RunnableExample implements Runnable {
boolean isAvailable = false;
Thread thread;
public RunnableExample() {
thread = new Thread(this);
thread.start();
}
public void run() {
isAvailable = checkForAvailability();
}
private boolean checkForAvailability() {
// some task
try {
Thread.sleep(1000);
} catch (Exception e) {
}
return true;
}
}
【问题讨论】:
-
问题是什么?
-
在
RunnableExample的构造函数中创建的本地线程不使用RunnableExample的方法run,因此也不会调用checkForAvailability。该线程应声明为:public RunnableExample() { new Thread(this).start();} -
@AlexRudenko run 方法将在 thread.start() 将在 RunnableExample() 构造函数中执行时执行。我正在 RunnableTest 类中创建 RunnableExample 类的对象。
-
@Srikant,不,它没有。没有为构造函数中启动的线程实例提供
RunnableExample(实现Runnable)的实例。 -
@AlexRudenko 对不起我的错误!更新了
标签: java multithreading java.util.concurrent