I really don’t like posting multiple questions in a go, sorry if this is annoying.
I finally managed to fix my problem. Except I’m not sure if it is reliable or even wise.
public void run() {
// TODO Auto-generated method stub
float time = 0.01f;
try {
while(time < timer)
{
time+=0.1f;
Thread.sleep(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (ProgressBar.class) {
int val =++ProgressBar.threadCount;
if(val == 10)
{
System.out.println("All threads are finished!") ;
}
}
}
}
I’ve been testing for 5mins now, and it seems to work.
But can someone explain what’s happening? When a thread is started, it makes sure that the synchronized block is not in use, otherwise it waits for it to be completed.
So is it some queueing system?
Thanks again.
EDIT:
Previous links
How does AtomicInteger work?
A
synchronizedblock uses the lock in the object that it refers to, in your caseProgressBar.class. If no other thread owns the lock, thesynchronizedblock acquires it and proceeds. If the lock already is owned by another thread, thesynchronizedblock goes to sleep to await the release of the lock, at which point it tries again. Once the thread that owns the lock finishes with thesynchronizedblock, it releases the lock, which causes at least one of the threads that are waiting for the lock to attempt to acquire it.(This explanation overlooks the possibility that the same thread may acquire a lock several times before releasing it. So long as the thread owns the lock at least once, all other threads are blocked from acquiring it.)
See the Java Language Specification.