【发布时间】:2015-05-07 19:11:18
【问题描述】:
我正在研究可重入锁并尝试将其与同步相关联。然而,这两个课程都给了我意想不到的结果。我期望 arrayList 有 0 到 9。但是这两个程序都不会出现这个值。请建议。 带锁:
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();
}
}
【问题讨论】:
-
你得到了什么输出?
标签: java multithreading java.util.concurrent