【发布时间】:2014-06-30 10:05:58
【问题描述】:
如果我写了以下类:
public class Thread1 extends thread{
int num;
OtherObject obj;
boolean isFinished;
public Thread1(int num, OtherObject obj){
this.num = num;
this.obj = obj;
isFinished = false;
}
public void run(){
this.startMethod();
}
public synchronize void startMethod(){
obj.anotherMethod()
if(isFinished !=true)
wait();
isFinished = true;
notifyAll();
}
public class main{
public static void main (String[] args){
OtherObject other = new OtherObject();
Thread1 first = new Thread1(1, other);
Thread1 second = new Thread1(2, other);
first.start();
second.start();
*这段代码没有逻辑意义,只是代表了synchronized、wait()、notify()的思想。
1) 同步方法何时同步运行。 “第一”和“第二”是不同的对象,那么它们会同步吗?或不? 还是因为他们有共享变量 - OtherObject obj 他们会被同步?
2) 当我写 wait() 时,让我们说线程“首先”对象将进入睡眠状态并在什么时候醒来?
仅当来自同一类的另一个对象执行了 notify() 时? 或者当程序中的任何对象调用 notify() 时? 如果我在“OtherObject”类中编写通知,它也会使“第一个”对象唤醒?
3)“startMethod”是同步的,因此,当我 start() 第一个和第二个线程时,它们会执行 run 方法并启动“startMethod”。
“startMethod”是否同步完成?可能是因为它转到内部的“另一个方法”(不是同步方法),还是因为它从“运行”开始,也不是同步的? 我不明白标记为已同步的方法何时会同步,在什么情况下会停止同步?
【问题讨论】:
-
不要试图让“没有逻辑意义”的代码多线程。具有逻辑意义的代码已经够难了。在您的情况下,您的代码似乎应该等到
isFinished是true并且然后 将isFinished设置为true。无论多线程如何,这都不起作用。关于synchronized,您是从错误的一端尝试。首先,您必须完全了解为什么需要synchronized。 There’s good literature around…
标签: java multithreading synchronization synchronized