how are static methods handled in a multithreaded environment?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   johannes_rainer
Posted On:   Tuesday, March 11, 2003 01:22 AM

how are static methods handled in a multithreaded environment?


assume i have a class Drawer with a static method public static drawCircle(Graphics g); Now there are two or more threads which are calling this method at the same time, everyone passing it's own Graphics object (the things which are painted by the method are not going to be shown on the screen!!!). what happens? do the calls perform simultaiously or does one thread have to wait until the other has finished calling the static method?
please help

Re: how are static methods handled in a multithreaded environment?

Posted By:   Jeff_Hubbach  
Posted On:   Tuesday, March 11, 2003 10:59 AM

The calls are allowed to perform simultaneously unless you explicitly force otherwise by using the synchronized keyword. If your method signature was public static synchronized drawCircle(Graphics g), then you would be guaranteed that only one thread of execution is in that method at any one time.

Re: how are static methods handled in a multithreaded environment?

Posted By:   bhagyshree_jayaram  
Posted On:   Tuesday, March 11, 2003 04:20 AM

The calls perform simultaniously.The threads don't have to wait for the other to finish calling the static method.Here is the code that I used for testing it and here is the output.

MyThread thread = new MyThread("First");
thread.start();
MyThread thread1 = new MyThread("Second");
thread1.start();

public void run(){
Drawer draw = new Drawer();
draw.drawCircle("Hello " + name_);
}


public class Drawer {
static int x =0;
/**
* Constructor for Drawer.
*/
public Drawer() {
super();
}
public static void drawCircle(String str){
x++;
System.out.println(str + x);
try{
Thread.sleep(1000);
}catch(Exception e){
}
x--;
System.out.println(str + x);

}
}

OutPut :

Hello First1
Hello Second2
Hello Second1
Hello First0



Hope this helps you....
About | Sitemap | Contact