The following SyncRun source code demonstrates what happens when you synchronize the run() method. If you run this program, you will notice that either thread A or thread B runs to completion before the other thread. That is due to the running thread holding the lock until it exits run(). As a result, the other thread delays its execution of that method. My question is: As there is no switching between the two Threads „A“ and „B“ because of synchronized run() method – Do I need the Thread.sleep() in the first place? I mean as synchronized doesn’t allow switching between Threads the sleep() method which stops one Thread to switch to the competing Thread is not neccessary. I tried it without sleep() and had – excpectedly – the same result, but the program ran much faster as The current Thread was not stopped by the sleep() method.
=> What do you think? DO I NEED the SLEEP() method here or is it without effect here?
C:\Java\EigeneJavaProgramme>java SyncRun A A A A A A B B B B B B
Joined: Jun 24, 2002
It works good - time schedule working. If you wish to switch the threads, you may try to: ------------------------------------------------ Thread.yield() public static void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute. ------------------------------------------------ Or use some kind of semaphore. There should be a lot of Java semaphores implementation here.
Joined: Oct 30, 2001
Methods like sleep() and yield() do not release the lock on the monitor. Only wait() does that. If your implementation of run() is a synchronised method and never does wait() then, once one thread is executing run(), any thread trying to execute run() on the same object would block. If run() were not a synchronised method, then methods like sleep() and yield() can suggest to the scheduler that another thread might get the CPU.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Running two threads with the same object is a mistake. You should have created an object per thread. If you insist on doing it, head Mr.Chase's remarks.
[ November 06, 2002: Message edited by: CL Gilbert ]
Joined: Mar 26, 2002
You can run different threads with the same object. Look at servlet container model, which uses one instances of servlet object for multiple requests utilizing different threads. About synchronized run method. There is nothing wrong with that either. You need to use wait/notify to check if resource is available. Normally you would have a loop within run and have some other resource to check. If resource is not available you call wait and let other thread enter run. You should have another method, which makes resource available, and calls notify to wake up thread.