gpt4 book ai didi

java - 来自线程的方法调用未完成 - 如何结束线程 - 解决方法

转载 作者:行者123 更新时间:2023-11-30 07:08:09 27 4
gpt4 key购买 nike

我有以下代码。

ReadWriteLock someLock = new ReentrantReadWriteLock();
Condition someCondition = someLock.writeLock().newCondition();

public someMethod() {
// do some stuff
someCondition.await(); //Lock here.
System.out.prinltn("This never prints");
}

public doSomeStuff() {
new Thread(new Runnable() {
@Override
public void run() {
try {
someMethod();
System.out.println("thread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread is going to die");
}
}).start();
}

当线程调用方法 someMethod() 时,它会被执行。但是由于该函数有一个 await() 方法。它永远不会结束/它不会打印“This never prints”,除非它被 singnalAll() 唤醒。但我希望线程在执行后完成。

我无法重构整个事情。我只需要解决此问题的方法。它用于 Swing 应用程序。所以线程很重要。

最佳答案

我认为,这样做会:

Thread thread =
new Thread(new Runnable() {
@Override
public void run() {
try {
someMethod();
System.out.println("thread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread is going to die");
}
});

thread.start( );

final long reasonableTimeout = ...;

thread.join( reasonableTimeout );

// THIS WILL SHAKE IT UP
thread.interrupt( );

thread.join( );

// At this point, it is guaranteed that the thread has finished

关于java - 来自线程的方法调用未完成 - 如何结束线程 - 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192998/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com