consider the below code.
public class MyThread extends Thread {
int limit;
public MyThread(int limit, String name) {
super();
this.limit = limit;
this.setName(name);
}
public void run() {
printValues();
}
private synchronized void printValues() {
for (int i = 1; i < limit; i++) {
System.out.println(currentThread().getName() + " No = " + i);
}
}
}
Requirement: If a thread starts execution of printValues(), suppose it has to print till 10000. Until it completes its job, no other thread should be able to enter this method.
For this I tried Lock interface as well not able to achieve this.
can anyone throw some inputs on this?
You time will be highly appreciated.
Putting synchronized means a thread has to acquire the lock (monitor) for the object instance. If you enforce only one instance of the object it stops concurrent execution.
Alternatively you can have a static lock to do the same thing
private static final Object lock = new Object();
public void printValues() {
synchronized(lock) {
//...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With