The Artima Developer Community
Sponsored Link

Legacy Design Forum
Thread Safety

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Synchronized

Posted by jonathan on July 13, 2001 at 4:35 AM

Dear pple,
I'm a bit confused on synchronization and multithreading.
I have a ResourceController class and a MyThread class which extends Thread.
public class MyThread extends Thread{
ResourceController myController;
long time;
public MyThread(ResourceController rc,long t){
myController = rc;
time=t;
}
public synchronized void run(){
try{

synchronized(myController){

while(myController.hasNoResource()){
wait();
}
//do some stuff, then myController.incrementAvailableResource();
notifyAll();
}
}catch(InterruptedException e){
e.printStackTrace();
}

}

public static void main(String[] args){
ResourceController r= new ResourceController(10);
long time=System.currentTimeMillis();
for(int i=0;i<30;i++){
//System.out.println("resource before thread starts is "+r.availableResource());
MyThread t= new MyThread(r,time);
t.start();
//System.out.println("resource after thread is finished is "+r.availableResource());
}


}
}
This runs fine, but it defeats the purpose of multithreading, since everything runs sychronized. I had to synchronize the method run because it was giving me IllegalMinitorException. I vague understanding is that if I synchronize run, then the threads can only access the method run's code in series, is that right?
So I'm confused and dont' know how to make it so that all threads run in parellel and also be controlled by the ResourceController, so that the number of threads running at the time same can only be a constant number which i specified.

would someone provide a concret code and explain what's wrong with what i did and my logic stuff?
thank you very much





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us