- 线程池
public class TestCallableAndFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newFixedThreadPool(2);
Callable<Integer> task1 = new Callable<Integer>(){
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 50; i++) {
sum += i;
}
return sum;
}
};
Callable<Integer> task2 = new Callable<Integer>(){
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 51; i <= 100; i++) {
sum += i;
}
return sum;
}
};
Future<Integer> f1 = es.submit(task1);
Future<Integer> f2 = es.submit(task2);
Integer result1 = f1.get();
Integer result2 = f2.get();
System.out.println(result1 + result2);
}
}
- 重入锁,读写锁
public class TestReentrantReadWriteLock {
public static void main(String[] args) {
final MyEntity me = new MyEntity();
Callable writeTask = new Callable(){
@Override
public Object call() throws Exception {
me.setValue(111);
return null;
}
};
Callable readTask = new Callable(){
@Override
public Object call() throws Exception {
me.getValue();
return null;
}
};
ExecutorService es = Executors.newFixedThreadPool(20);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 2; i++) {
es.submit(writeTask);
}
for (int i = 0; i < 18; i++) {
es.submit(readTask);
}
es.shutdown();
while(!es.isTerminated()){
System.out.println("未完成...");
}
long endTime = System.currentTimeMillis() - startTime;
System.out.println(endTime);
}
}
class MyEntity{
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
ReadLock rl = rwl.readLock();
WriteLock wl = rwl.writeLock();
private Integer value = 0;
public void setValue(Integer value) throws InterruptedException{
wl.lock();
try {
Thread.sleep(1000);
this.value = value;
} finally{
wl.unlock();
}
}
public Integer getValue() throws InterruptedException{
rl.lock();
try {
Thread.sleep(1000);
return this.value;
} finally{
rl.unlock();
}
}
}
- 队列, 解决生产者,消费者问题
public class TestArrayBlockingQueue {
public static void main(String[] args) {
final BlockingQueue<Character> bq = new LinkedBlockingQueue<Character>();
Callable task1 = new Callable() {
@Override
public Object call() throws Exception {
for (char c = 'A'; c <= 'Z'; c++) {
bq.put(c);
System.out.println("Put :" + c);
}
return null;
}
};
Callable task2 = new Callable() {
@Override
public Object call() throws Exception {
for (int i = 0; i < 26; i++) {
System.out.println("Take :" + bq.take());
}
return null;
}
};
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(task1);
es.submit(task2);
}
}