Reputation: 6591
is it possible to execute same function concurrently from thread. I have doubt that in java method area is same so the multiple call to same function may lead to waiting state , am i correct?
Upvotes: 0
Views: 2462
Reputation: 20323
yes, it is possible unless you have used synchronization there wont be any waiting for lock. This is the default behavior, no locking and thread execution can be interleaved.
Though remember that your thread scheduler will allow one thread to run at a given time.
By default in absence of synchronization concurrent access without wait is the behavior.
Sample to demostrate
public class MyThread implements Runnable {
private MyThreadInvocation threadInvocation = null;
public MyThread(MyThreadInvocation threadInvocation) {
this.threadInvocation = threadInvocation;
}
@Override
public void run() {
System.out.println("Calling from : " + Thread.currentThread().getName());
this.threadInvocation.printMessage();
}
}
public class MyThreadInvocation {
public void printMessage(){
System.out.println("Hello");
}
public static void main(String[] args) {
MyThreadInvocation myThreadInvocation = new MyThreadInvocation();
Thread t1 = new Thread(new MyThread(myThreadInvocation));
t1.setName("First Thread");
Thread t2 = new Thread(new MyThread(myThreadInvocation));
t2.setName("Second Thread");
Thread t3 = new Thread(new MyThread(myThreadInvocation));
t3.setName("Third Thread");
t1.start();
t2.start();
t3.start();
}
}
Upvotes: 1
Reputation: 106391
Yes, it is perfectly possible to call the same function concurrently from multiple threads. Each thread has it's own stack, which means that it gets it's own copy of local variables used in the function.
On a multi-core machine the threads may even be running simultaneously in the same function.
Of course, calling the same function concurrently from multiple threads can cause problems if they access the same mutable state (e.g. a field in an object that both threads read and write to). If you want to protect against these issues, you will need to use some form of locking or synchronisation.
Upvotes: 1
Reputation: 1125
Yeap. you can do the concurrent execution of method by default. To stop the concurrent execution you need to use the synchronized key word or concurrency classes
Upvotes: 2