This is related to threads. I have a class with synchronized
method m1(). Can I create different instances of this class
and execute the m1() for different threads?
Answers were Sorted based on User's Feedback
Answer / shashidhar
When a thread enters the Synchronized method the object on
this the method is called gets locked so no other thread
cannot cal that or any other method on same object.
| Is This Answer Correct ? | 4 Yes | 1 No |
Answer / qim2010
Putting code inside a synchronized block makes the compiler
append instructions to acquire the lock on the specified
object before executing the code, and release it afterwards
(either because the code finishes normally or abnormally).
Between acquiring the lock and releasing it, a thread is
said to "own" the lock. At the point of Thread A wanting to
acquire the lock, if Thread B already owns the it, then
Thread A must wait for Thread B to release it. Thus in the
example below, simultaneous calls to increment() and
getCount() will always behave as expected; a read could not
"step in" while another thread was in the middle of
incrementing.
public class Counter {
private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
public int getCount() {
synchronized (this) {
return count;
}
}
}
| Is This Answer Correct ? | 0 Yes | 0 No |
Answer / haneef
see by the synchronized it won't allow the other thread at a
time, but after completion of 1st thread it allows, so you
can create different instances.
see the following code
package app;
class C1 extends Thread {
public void run() {
m1();
}
public synchronized void m1() {
System.out.println("m1()");
}
}
public class Main {
public static void main(String[] args) {
C1 c1 = new C1();
C1 c2 = new C1();
C1 c3 = new C1();
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
Thread t3 = new Thread(c3);
t1.start();
t2.start();
t3.start();
}
}
| Is This Answer Correct ? | 0 Yes | 1 No |
Can string be considered as a keyword?
Can we use a switch statement with strings?
When is an object subject to garbage collection?
Why cant we define System.out.println() inside a class directly?
Name the packages in JDK?
Why wait(),notify(),notifyAll() methods defined in Object class althought we are using in only threads.
what is deadlock? : Java thread
Implement two stacks using a single array.
java can provide security ,how can provide?
8 Answers Aspire, BNP Paribas, Genpact, IBM,
What is the difference between hashmap and hashtable? What is an interface?
What is difference in between java class and bean?
What do you mean by JVM?