Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Lock A block of code for a Thread in Java

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.

like image 397
Abdul Avatar asked Nov 21 '25 20:11

Abdul


1 Answers

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) {
        //...
    }
}
like image 126
Nick Cardoso Avatar answered Nov 23 '25 10:11

Nick Cardoso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!