0% found this document useful (0 votes)
2 views2 pages

Synchronization WithLock

The document contains a Java program that demonstrates the use of locks for synchronizing access to a shared resource, specifically a counter. It includes classes for adding and subtracting values from the counter in separate threads, ensuring thread safety with a ReentrantLock. The main method initializes the counter and starts both threads, printing the final value of the counter after both operations are complete.

Uploaded by

abhinavstar3909
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Synchronization WithLock

The document contains a Java program that demonstrates the use of locks for synchronizing access to a shared resource, specifically a counter. It includes classes for adding and subtracting values from the counter in separate threads, ensuring thread safety with a ReentrantLock. The main method initializes the counter and starts both threads, printing the final value of the counter after both operations are complete.

Uploaded by

abhinavstar3909
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

package WithSyncLock;

import [Link].*;
import [Link];
import [Link];

public class Client {


public static void main(String[] args) throws Exception{
Count count=new Count();

Lock lock=new ReentrantLock();

Adder ad=new Adder(count,lock);


Subtractor sb=new Subtractor(count,lock);

Thread t1=new Thread(ad);


Thread t2=new Thread(sb);

[Link]();
[Link]();

[Link]();
[Link]();

[Link]([Link]);
}
}
package WithSyncLock;

public class Count {


int value=0;
}
package WithSyncLock;
import [Link];

public class Adder implements Runnable{


private Count count;
private Lock lock;
public Adder(Count count,Lock lock){
[Link]=count;
[Link]=lock;
}
@Override
public void run() {

for(int i=0;i<10;i++){
[Link]();
[Link]=[Link]+i;
[Link]([Link]);
[Link]();
}

}
}
package WithSyncLock;
import [Link];

public class Subtractor implements Runnable{


private Count count;
private Lock lock;
public Subtractor(Count count,Lock lock){
[Link]=count;
[Link]=lock;
}
@Override
public void run() {
for(int i=0;i<10;i++){
[Link]();
[Link]=[Link]-i;
[Link]([Link]);
[Link]();
}
}
}

You might also like