线程笔记之并发同步(二)

2014-11-24 01:34:22 · 作者: · 浏览: 2
tem.currentTimeMillis();

monitor.require(2); //初始化信号量
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
cst.method1();
} finally {
monitor.release(1); //信号量-1
}
}
});

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
cst.method2();
} finally {
monitor.release(1); //信号量-1
}
}
});

t1.start();
t2.start();

synchronized (monitor) {
while (monitor.single > 0) {
monitor.wait(); // monitor.wait(10 * 1000), 进行超时异常处理,中断t1,t2
}
}
//线程1/2都已返回,需要验证结果
long s3 = System.currentTimeMillis();

System.out.println("time cost for normal execution:" + (s2 - s1));
System.out.println("time cost for concurrent execution:" + (s3 - s2));
}


使用JDK concurrent包中的信号量对象Semaphores
Java代码
public static void main(String[] args) throws InterruptedException {
final ConcurrentSimpleTest cst = new ConcurrentSimpleTest();
final Semaphore monitor = new Semaphore(0);

long s1 = System.currentTimeMillis();
cst.method1();
cst.method2();
long s2 = System.currentTimeMillis();

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
cst.method1();
} finally {
monitor.release(); //增加信号量
}
}
});

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
cst.method2();
} finally {
monitor.release(); //增加信号量
}
}
});

t1.start();
t2.start();

monitor.acquireUninterruptibly(2); //tryAcquire(int permits, long timeout, TimeUnit unit) 可设置超时处理

//线程1/2都已返回,需要验证结果

long s3 = System.currentTimeMillis();

System.out.println("time cost for normal execution:" + (s2 - s1));
System.out.println("time cost for concurrent execution:" + (s3 - s2));
}


使用JDK concurrent包中的信号量对象CountDownLatch(似乎比Semaphores更适合这种场景)
Java代码
public static void main(String[] args) throws InterruptedException {
final ConcurrentSimpleTest22 cst = new ConcurrentSimpleTest22();
final CountDownLatch monitor = new CountDownLatch(2); //设置计数器

long s1 = System.currentTimeMillis();
cst.method1();
cst.method2();
long s2 = System.currentTimeMillis();

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
cst.method1();
} finally {
monitor.countDown(); //计数器-1
}
}
});

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
cst.method2(