Then there is any guarante, isn't it? Although there are only two threads I can't assume that if one is sleeping for 5 seconds the other get the CPU? This changes if the other thread has more priority?
In general, how can I be sure that another thread will get the cpu? (only with synchronized,wait,notify), with yield/sleep with priorities?
posted 14 years ago
Basically the idea of threads is to get lots of things going on at the same time (either apparently on one CPU or really on a multi-CPU computer). wait, notify, notifyAll are used to keep threads from corrupting common resources. yield, sleep, priorities, join are used to suggest to the thread scheduler (implementation, operating system, hardware dependent) a scheduling order. In my opinion you should program threads with that in mind - you want things to happen at the same time - and not be a thread scheduler.
You may be interested in the Java 5.0 java.util.concurrent package classes to see what you can use for sharing resources between threads (also see Henry Wong's Java Threads book). The new classes are not part of SCJP 5.0 however (a shame). [ October 20, 2005: Message edited by: Barry Gaunt ]
I know what you mean. In the real world I think that if you yield() or sleep() and you have two threads of the same priority you will obtain concurrency in practically any platform and situation, and that's all.
But in the exam, sometimes you need to do be a thread scheduler, don't you? And my question was mainly with the exam in mind.
posted 14 years ago
For the real examination I think it's fair to say that you will have to choose between a clear case of nondeterministic behaviour (unsynchronized or synchronized on distinct objects) and deterministic behaviour synchronized on one object (explicit or implicit). You should know that no guarantees exist for yield, sleep, priorities. Also that calling the run method of a thread does not change thread context. [ October 20, 2005: Message edited by: Barry Gaunt ]