다음 코드가 있습니다.스레드에서 메소드 호출이 완료되지 않음 - 스레드 종료 방법 - 해결 방법
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()
방법이 있기 때문에. 그것은 결코 끝나지 않습니다/singnalAll()
에 의해 깨우지 않는 한 'This never prints'를 인쇄하지 않습니다. 하지만 스레드가 실행되면 끝내기를 원합니다.
저는 모든 것을 리펙토링 할 수 없습니다. 이 문제에 대한 해결 방법이 필요합니다. 스윙 응용 프로그램에 사용됩니다. 그래서 스레드가 중요합니다.
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
메서드 호출에 관련 스레드가 있어야합니다. 현재 스레드를 풀어 끝내기를 원한다면 다른 스레드를 만들고 그 스레드에서 메서드를 호출해야합니다. –
@JigarJoshi는 정교하게 처리합니까? –
업데이트 (조심 :)) –