怎样才能实现真正的异步Java线程 [英] How does one implement a truly asynchronous java thread
问题描述
我有一个需要它进行两个操作,其中一个完成快速和一个这需要很长的时间来执行的功能。我希望能够委派长时间运行操作线程,我不关心,当线程完成,但线程需要完成。我实现了这个如下图所示,但是,我从来没有secondoperation得到执行的函数调用start()后退出。我如何能确保该函数返回,但第二次手术线程完成它的执行,以及和不依赖于父线程?
在 公共无效someFunction(字符串数据)
{
smallOperation()
SecondOperation一个=新SecondOperation();
主题日=新主题(一);
th.Start();
}类SecondOperation实现Runnable
{
公共无效的run(){
// DoSomething的长时间运行
}
}
公共无效someFunction(最终字符串数据){
shortOperation(数据);
新主题(新的Runnable接口(){
公共无效的run(){
longOperation(数据);
}
})。开始();
}
如果 someFunction
被调用时,JVM将执行 longOperation
如果
- 运行它的线程没有标记
作为一个的后台的(在上面的code将其
是不是) - 在
longOperation()
不抛出异常和 - 对System.exit没有()的调用在
longOperation(由)
I have a function that needs to perfom two operations, one which finishes fast and one which takes a long time to run. I want to be able to delegate the long running operation to a thread and I dont care when the thread finishes, but the threads needs to complete. I implemented this as shown below , but, my secondoperation never gets done as the function exits after the start() call. How I can ensure that the function returns but the second operation thread finishes its execution as well and is not dependent on the parent thread ?
public void someFunction(String data)
{
smallOperation()
SecondOperation a = new SecondOperation();
Thread th = new Thread(a);
th.Start();
}
class SecondOperation implements Runnable
{
public void run(){
// doSomething long running
}
}
public void someFunction(final String data) {
shortOperation(data);
new Thread(new Runnable() {
public void run(){
longOperation(data);
}
}).start();
}
If someFunction
is called, the JVM will run the longOperation
if
- the thread running it is not marked as a daemon (in the above code it is not)
- the
longOperation()
does not throw an exception and - no calls to System.exit() is made in
longOperation()
这篇关于怎样才能实现真正的异步Java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!