Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.locks.ReentrantLock;
- class Program {
- public static void main(String[] args) throws InterruptedException{
- Number n = new Number(0);
- int cnt = 100;
- Thread[] th = new Thread[cnt];
- for (int i = 0; i < cnt; i++){
- th[i] = new Thread(new Increment(n));
- }
- for (int i = 0; i < cnt; i++){
- th[i].start();
- }
- for (int i = 0; i < cnt; i++){
- th[i].join();
- }
- System.out.println("Number = " + (n.value));
- }
- }
- class Increment implements Runnable {
- Number num;
- public Increment (Number n){
- this.num = n;
- }
- @Override
- public void run() {
- for (int i = 0; i < 100; i++){
- num.increment(); // i++
- }
- }
- }
- class Number {
- ReentrantLock lock = new ReentrantLock();
- public int value;
- public Number(int value){
- this.value = value;
- }
- public synchronized void increment(){
- // lock.lock();
- this.value++;
- // lock.unlock();
- }
- }
Add Comment
Please, Sign In to add comment