使用Lock,对不同商品加锁
package com.boce.gbkutf;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.ibm.icu.util.Calendar;
//实现多key值多锁,如 key=12,已经加锁(HashMap 中存在),其它线程就不可以对key=12,进行操作,线程阻塞,需要等当前线程操作完成后,其它线程才可以操作.
package com.boce.gbkutf;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.ibm.icu.util.Calendar;
public class MutiLock {
final Lock lock = new ReentrantLock();//锁对象
final Condition notFull = lock.newCondition();//写线程条件
final Condition notEmpty = lock.newCondition();//读线程条件
//lock数量
final Map<String,String> items = new HashMap<String,String>(100);//缓存队列
//锁定某个商品id
public void put(String x) throws InterruptedException {
lock.tryLock(1000L, TimeUnit.SECONDS); //锁定6秒钟
try {
while (x == items.get(x)){//如果已经存在对象
notFull.await();//阻塞写线程
System.out.println("time:"+Calendar.getInstance().getTimeInMillis());
}
items.put(x, x);//赋值
System.out.println("put:"+x);
} finally {
lock.unlock();
}
}
//释放某个锁定的商品id
public void take(String key) throws InterruptedException {
lock.tryLock(1000L, TimeUnit.SECONDS);
try {
notFull.signal();//唤醒写线程
items.remove(key);
System.out.println("================get:"+key);
} finally {
lock.unlock();
}
}
}
//测试类
package com.boce.gbkutf;
import java.util.Random;
public class ThreadTest implements Runnable{
private String key;
private MutiLock mutiLock;
public ThreadTest(String key, MutiLock mutiLock) {
super();
this.key = key;
this.mutiLock = mutiLock;
}
@Override
public void run() {
try {
mutiLock.put(key);
Random rand = new Random();
int data = rand.nextInt(2000);
System.out.println("key:"+key+";工作时间:"+data);
//模拟工作时长
Thread.sleep(data);
mutiLock.take(key);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.boce.gbkutf;
public class TestMain {
public static void main(String[] args) {
MutiLock mutiLock = new MutiLock();
for (int i = 0; i < 2; i++) {
String key = "123456";
ThreadTest test = new ThreadTest(key, mutiLock);
Thread test1 = new Thread(test);
test1.start();
String key1 = "123456"+i;
ThreadTest test11 = new ThreadTest(key1, mutiLock);
Thread test12 = new Thread(test11);
test12.start();
}
}
}
测试日志:
put:123456
put:1234561
key:123456;工作时间:660
put:1234560
key:1234561;工作时间:795
key:1234560;工作时间:1090
================get:123456
time:1489373212371
put:123456
key:123456;工作时间:419
================get:1234561
================get:1234560
================get:123456