wor*_*cle 5 java multithreading
@Component
class Type
{
@PostConstruct
private void postConstructor() {
Runnable threadAlpha = () -> {
while (true) {
workWithSomething();
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
}
}
};
Runnable threadBeta = () -> {
while (true) {
workWithOtherthing();
try {
Thread.sleep(1000 * 3);
} catch (InterruptedException e) {
}
}
};
threadBeta.run();
threadAlpha.run();
}
}
Run Code Online (Sandbox Code Playgroud)
使用 spring-framework,我正在努力处理这段代码,问题是只有一个线程实际上可以run()首先调用,另一个线程似乎冻结,如果我将位置切换为:
threadAlpha.run();
threadBeta.run();
Run Code Online (Sandbox Code Playgroud)
然后threadBeta就一直没有启动,为什么会出现这样的情况呢?
因为你没有创建线程。相反,您创建Runnable实例然后运行它们的run方法。
相反,这样做:
new Thread(threadAlpha).start();
new Thread(threadBeta).start();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1595 次 |
| 最近记录: |