I am working on Re entrant locks and trying to correlate it with Synchronize. However both these classes are giving me unexpected results. I am expecting the arrayList to have 0 to 9. but that value never comes in both these programs. Please suggest. With lock:
package Threads;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Locking {
Lock lock = new ReentrantLock(true);
ArrayList<Integer> al = new ArrayList<Integer>();
static int count = 0;
public void producer() {
lock.lock();
count++;
al.add(count);
System.out.println(al);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
// System.out.println("I came out of this block:"+Thread.currentThread().getName());
}
public void consumer() {
}
public static void main(String[] args) {
// ExecutorService ex= Executors.newCachedThreadPool();
ExecutorService ex = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
ex.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Locking().producer();
}
});
}
ex.shutdown();
}
}
With synchronize:
package Threads;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LockwithSynchronize {
ArrayList<Integer> al = new ArrayList<Integer>();
static int count = 0;
public synchronized void producer() {
count++;
al.add(count);
System.out.println(al);
try {
Thread.sleep(5000);
// System.out.println("I came out of this block:"+Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// ExecutorService ex= Executors.newCachedThreadPool();
ExecutorService ex = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
ex.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new LockwithSynchronize().producer();
}
});
}
ex.shutdown();
}
}