标签:ble cached executor shu exec oid task 码农 locker
将做工程过程重要的代码段做个记录,如下的代码内容是关于Java多线程编程中的lock使用详解的代码,应该是对码农有帮助。import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Lockers {
public static class LockTest {
int addtimes = 0;
public void addValue(double v) {
System.out.println("LockTest to addValue: " + v + " "
+ System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
this.value += v;
this.addtimes++;
}
public double getValue() {
return this.value;
}
}
public static void testLockTest() throws Exception{
final LockTest lockTest = new LockTest();
Runnable task1 = new Runnable(){
public void run(){
lockTest.addValue(55.55);
}
};
Runnable task2 = new Runnable(){
public void run(){
System.out.println("value: " + lockTest.getValue());
}
};
ExecutorService cachedService = Executors.newCachedThreadPool();
Future future = null;
for (int i=0; i<3; i++){
future = cachedService.submit(task1);
}
future.get();
future = cachedService.submit(task2);
future.get();
cachedService.shutdownNow();
}
public static class ReadWriteLockTest{
ReadWriteLock lock = new ReentrantReadWriteLock();
double value = 0d;
int addtimes = 0;
public void addValue(double v) {
Lock writeLock = lock.writeLock();
writeLock.lock();
System.out.println("ReadWriteLockTest to addValue: " + v + " "
+ System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
this.value += v;
this.addtimes++;
} finally {
writeLock.unlock();
}
}
public String getInfo() {
Lock readLock = lock.readLock();
readLock.lock();
System.out.println("ReadWriteLockTest to getInfo "
+ System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
return this.value + " : " + this.addtimes;
} finally {
readLock.unlock();
}
}
}
public static void testReadWriteLockTest() throws Exception{
final ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
Runnable task_1 = new Runnable(){
public void run(){
readWriteLockTest.addValue(55.55);
}
};
Runnable task_2 = new Runnable(){
public void run(){
System.out.println("info: " + readWriteLockTest.getInfo());
}
};
ExecutorService cachedService_1 = Executors.newCachedThreadPool();
Future future_1 = null;
for (int i=0; i<2; i++){
future_1 = cachedService_1.submit(task_1);
}
for (int i=0; i<2; i++){
future_1 = cachedService_1.submit(task_2);
}
future_1 = cachedService_1.submit(task_1);
future_1.get();
cachedService_1.shutdownNow();
}
public static void main(String[] args) throws Exception{
Lockers.testLockTest();
System.out.println("---------------------");
Lockers.testReadWriteLockTest();
}
}
标签:ble cached executor shu exec oid task 码农 locker
原文地址:http://blog.51cto.com/14118518/2348944