【发布时间】:2010-06-12 03:34:15
【问题描述】:
在 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()
}
}
}
为什么?
【问题讨论】:
-
21 个问题,3 个接受的答案。他们真的都那么糟糕吗?
标签: java synchronized