在 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) 在单独的线程中启动一个操作,然后等待其完成——好的,这不完全正确,否则可以使用 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();
}
}
}
}
这段代码可以吗,还是我仍然遇到潜在问题?有什么更好的解决方法?
米莎
我想知道,这是正确的:
选项一
class A {
public void methodOne() {
synchronized(this) {
modifyvalue
notifyAll()
}
}
public void methodTwo() {
while (valuenotmodified) {
synchronized(this) {
wait()
}
}
}
选项二
class A {
public void methodOne() {
modifyvalue
synchronized(this) {
notifyAll()
}
}
public void methodTwo() {
while (valuenotmodified) {
synchronized(this) {
wait()
}
}
}
为什么?