我正在研究可重入锁,并试图将其与Synchronize相关联。但是这两个类都给我带来了意外的结果。我期望arrayList中有0到9的值,但是在这两个程序中从未出现过。请建议。
使用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();
}
}
使用同步:
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();
}
}