一 Lock锁的介绍
用法示例代码
public class LockTest {
public static void main(String[] args) {
new LockTest().init();
}
private void init() {
final OutPuter outputer = new OutPuter();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("pengyunle");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lichengli");
}
}
}).start();
}
class OutPuter{
//要用的是同一把锁
Lock lock = new ReentrantLock();
public void output(String name) {
int len = name.length();
lock.lock();
//为了防止线程抛异常,跳出程序没有释放锁.需要铺获异常 加finally
try {
for(int i= 0;i<len;i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}finally {
lock.unlock();
}
}
}
}
二 读写锁
设计一个缓存系统,写出伪代码
public class CacheDemo {
private Map<String,Object> cacheMap = new HashMap<String,Object>();
/*
* 设计一个缓存系统,写出伪代码
*/
public static void main(String[] args) {
}
//多个用户去缓存访问读数据,也有浏览写数据.并发用到读写锁
private ReadWriteLock rw1 = new ReentrantReadWriteLock();
public Object getDtat(String key) {
rw1.readLock().lock();
Object value = null;
try {
value = cacheMap.get(key);
if(value == null) {
rw1.readLock().unlock();
rw1.writeLock().lock();
try {
if(value == null) {
value = "aaa"; //实际是去数据库里面查
}
}finally {
rw1.writeLock().unlock();
}
rw1.readLock().lock();
}
}finally {
rw1.readLock().unlock();
}
return value;
}
}
三 Condition线程通讯
public class ConditionCommunication {
//子线程循环10次,主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
public static void main(String[] args) {
final Business business =new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int j = 1; j <=50 ;j++) {
business.sub(j);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int j = 1; j <=50 ;j++) {
business.main(j);
}
}
}).start();
}
static class Business{
Lock lock = new ReentrantLock(); //多线程同步
Condition condition = lock.newCondition(); //多线程通讯
private boolean shelud = true;
public void sub(int j) {
lock.lock();
try {
while(!shelud) {
try {
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for(int i=1;i<=10;i++) {
System.out.println("sub thread sequnce of "+i+","+"loop of "+j);
}
shelud = false;
condition.signal();
}finally {
lock.unlock();
}
}
public void main(int j) {
lock.lock();
try {
while(shelud) {
try {
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for(int i=1;i<=100;i++) {
System.out.println("main thread sequnce of "+i+","+"loop of "+j);
}
shelud = true;
condition.signal();
}finally {
lock.unlock();
}
}
}
}