Groovyコードでは、次のような単純なものがあります:#!/ usr / bin / env groovy
public class test {
boolean val
def obj=new Object()
def dos() {
val=false
Thread.start() {
synchronized(obj) {
val=true
obj.notifyAll()
}
}
Thread.sleep(5000)
synchronized(obj) {
while (!val) {
obj.wait()
}
}
}
static void main(String[] args) {
def t=new test()
t.dos()
}
}
わかりました、これが私の問題です。
スレッド(A)は別のスレッドでアクションを開始し、その完了を待ちます-OKこれは正確には正しくありません。それ以外の場合はthread.join()を使用できます。このスレッドは実際にタスクを開始し、それが最終的にmethodOneに信号を送ります
スレッド(B)アクションが完了するとシグナルを受け取ります
class A {
private boolean finished
public synchronized void methodOne() {
finished=true;
notifyAll();
}
public void methodTwo() {
new ThreadThatCallsMethodOneWhenDone().start();
synchronized(this) {
while (!finished) {
wait();
}
}
}
}
このコードは大丈夫ですか、それともまだ潜在的な問題が発生していますか?解決するためのより良い方法は何ですか?
ミーシャ
私は疑問に思っていました、それは正しいです:
オプション1
class A {
public void methodOne() {
synchronized(this) {
modifyvalue
notifyAll()
}
}
public void methodTwo() {
while (valuenotmodified) {
synchronized(this) {
wait()
}
}
}
オプション2
class A {
public void methodOne() {
modifyvalue
synchronized(this) {
notifyAll()
}
}
public void methodTwo() {
while (valuenotmodified) {
synchronized(this) {
wait()
}
}
}
なぜ?