If I wrote the following classes:
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(); *this code doesn't has logic meaning, but to represent the idea of synchronized, wait(), notify().
1) When will the synchronized method run synchronized. "first" and "second" are different objects, so will they be synchronized? or not? or because they have shared variable - OtherObject obj they will be synchronized?
2) When I write wait() lets say for thread "first" the object will go to sleep and wake up when?
only when another object from the same class has done the notify()? or also when any object in the program will call notify()? and if I write the notify in "OtherObject" class it will also make "first" object to wake up?
3) The "startMethod" is synchronized, because of it, when I start() the first and second threads then they do the run method and start the "startMethod".
The "startMethod" will be done as synchronized or not? maybe because it goes to "anotherMethod" (that is not synchronized method) inside or because it started from "run" that is not synchronized also? I didn't understand when method that is marked as synchronized will be synchronized and in which circumstances it will stop being synchronized?
isFinishedistrueand then setisFinishedtotrue. That doesn’t work in any way, regardless of multi-threading. Regardingsynchronized, you are trying it from the wrong end. First you have to understand why you needsynchronizedat all. There’s good literature around…