解决并发问题

110 篇文章 0 订阅
11 篇文章 0 订阅

总结一下,也就是说Lock提供了比synchronized更多的功能。但是要注意以下几点:

  1)Lock不是Java语言内置的,synchronized是Java语言的关键字,因此是内置特性。Lock是一个类,通过这个类可以实现同步访问;

  2)Lock和synchronized有一点非常大的不同,采用 synchronized不需要用户去手动释放锁,当synchronized方法或者synchronized代码块执行完之后,系统会自动让线程释放 对锁的占用;而Lock则必须要用户去手动释放锁,如果没有主动释放锁,就有可能导致出现死锁现象。

 

2.ReentrantLock

  ReentrantLock,意思是“可重入锁”,关于可重入锁的概念在下一节讲述。ReentrantLock是唯一实现了Lock接口的类,并且ReentrantLock提供了更多的方法。下面通过一些实例看具体看一下如何使用ReentrantLock。

Lock lock = new ReentrantLock();   

lock.lock();

lock.unlock();

3.ReadWriteLock

  ReadWriteLock也是一个接口,在它里面只定义了两个方法:

4.ReentrantReadWriteLock

  ReadWriteLock接口,ReentrantReadWriteLock里面提供了很多丰富的方法,不过最主要的有两个方法:readLock()和writeLock()用来获取读锁和写锁。

ReadWriteLock lock = new ReentrantReadWriteLock(); 

 

Lock writeLock = lock.writeLock();  
writeLock.lock();

writeLock.unlock();

 

Lock readLock = lock.readLock();  
readLock.lock();

readLock.unlock();

5.Lock和synchronized的选择

  总结来说,Lock和synchronized有以下几点不同:

  1)Lock是一个接口,而synchronized是Java中的关键字,synchronized是内置的语言实现;

  2)synchronized在发生异常时,会自动释放线程占有的锁,因此不会导致死锁现象发生;而Lock在发生异常时,如果没有主动通过unLock()去释放锁,则很可能造成死锁现象,因此使用Lock时需要在finally块中释放锁;

  3)Lock可以让等待锁的线程响应中断,而synchronized却不行,使用synchronized时,等待的线程会一直等待下去,不能够响应中断;

  4)通过Lock可以知道有没有成功获取锁,而synchronized却无法办到。

  5)Lock可以提高多个线程进行读操作的效率。

  在性能上来说,如果竞争资源不激烈,两者的性能是差不多的,而当竞争资源非常激烈时(即有大量线程同时竞争),此时Lock的性能要远远优于synchronized。所以说,在具体使用时要根据适当情况选择。

package com.yanshu.controller;


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import com.alibaba.fastjson.JSON;
import com.yanshu.dao.CategoryLeafKeywordsDao;
import com.yanshu.dao.LogkeywordsDao;
import com.yanshu.pojo.CategoryLeafKeywords;
import com.yanshu.pojo.ComtyinfoDistinct;
import com.yanshu.pojo.LcsyGoodsinfodistinct;
import com.yanshu.pojo.Logkeywords;
import com.yanshu.pojo.OpenCate;
import com.yanshu.utils.DigitUtils;
import com.yanshu.utils.JsonUtil;
import com.yanshu.utils.MessageUtils;
import com.yanshu.utils.StringUtils;
import java.util.Map.Entry;
/**
 * 类别叶关键词
 * @author Administrator
 *叶子类目关键词索引表
 */
@RestController
@CrossOrigin
public class CategoryLeafController {
@Autowired
private CategoryLeafKeywordsDao clkdao;

@Autowired
private LogkeywordsDao logdao;
List<Map<String,Object>> ltcids=new ArrayList<>();
Map<String,Object> mcids=new HashMap<>();
public CategoryLeafController() {
// TODO Auto-generated constructor stub
}
//private static final Queue<CategoryLeafKeywords> queueAll = new LinkedList<>();
private static final PriorityQueue<CategoryLeafKeywords> queueAll = new PriorityQueue<CategoryLeafKeywords>();

public static PriorityQueue<CategoryLeafKeywords> getInstance() {   
return  queueAll;  
 }
private static final SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMdd");
// 锁  
    ReadWriteLock lock = new ReentrantReadWriteLock(); 
    Lock readLock = lock.readLock();  
/**
* http://localhost:8080/spiderQue/getkey?num=100
* http://211.95.60.40:16868/spiderQue/getkey?num=100
* @return 
*/
@RequestMapping(value="/getkey", method = { RequestMethod.GET,RequestMethod.POST }, produces = "application/json; charset=utf-8")
public synchronized String getCategoryLeafKeywords(String num)
{
// 得到readLock并锁定  
      //  readLock.lock();  
try{
List<CategoryLeafKeywords> returnUsers;
Integer incount;
if(StringUtils.isNullorEmpty(num))
{
return JsonUtil.errorMessages(1);
}
else
{

String strtime=dateFormat1.format(new Date());
Map map=new HashMap();
map.put("operationTime", strtime); 
//获取的时间
//查询到最大的时间
List<Logkeywords> loglist=logdao.findByLogkeywords(map);
//获得数据---从数据
boolean result = false;
       for(String key:mcids.keySet()){
         if(strtime.equals(mcids.get(key))){
               result=true;
               break;
           }
       }
if(loglist.size()<1)
{
//根据用户传递的ID 查询,把数据存到队列里面去
List<CategoryLeafKeywords> findcakw=clkdao.findBykeyword();
for (CategoryLeafKeywords object : findcakw) {
queueAll.offer(object);
}
clkdao.updateKeywordsAll();
//保存当前,日期和,用户传递的ID到日志表
logdao.save(map);
mcids.put(strtime, strtime);
}
//从队列里面拿数据
returnUsers= new ArrayList<>();
incount = Integer.parseInt(num); 
for (int i = 1; i<=incount; i++) {
if(queueAll.size()>1){
returnUsers.add(queueAll.poll());
}
}
//System.out.println("队列为了==="+queueAll.size());
    /*   if(queueAll.size()<=0)
       { //System.out.println("队列走==="+queueAll.size());
        //根据用户传递的ID 查询,把数据存到队列里面去
List<CategoryLeafKeywords> findcakw=clkdao.findBykeyword();
for (CategoryLeafKeywords object : findcakw) {
queueAll.offer(object);
}
clkdao.updateKeywordsAll();
//从队列里面拿数据
returnUsers= new ArrayList<>();
incount = Integer.parseInt(num); 
for (int i = 1; i<=incount; i++) {
if(queueAll.size()>1){
returnUsers.add(queueAll.poll());
}
}
       }*/ 
return returnUsers.size()!=0?JSON.toJSONString(returnUsers):JsonUtil.errorMessages(8);
}
}
finally
{
// 释放readLock  
            readLock.unlock();  
}

}
@RequestMapping("/fkdqcount")
public int getQueueSelect()
{
int size = queueAll.size();
if(size==1)
{
return 0;
}
else
{
return size;
}
}
@RequestMapping("/fkdqClear")
public String getClearQueue()
{
queueAll.clear();
return JSON.toJSONString("该队列已经清空!!!");
}
/**
* http://localhost:8080/spiderQue/upKeywords?cdid=1,2,3,4,5 
* @param cdid
* @return
*/
@RequestMapping(value="/upKeywords", method = { RequestMethod.GET,RequestMethod.POST }, produces = "application/json; charset=utf-8")
public String updateDate(String cdid)
{

if(StringUtils.isNullorEmpty(cdid))
{
return MessageUtils.errorMessages(1);
}else
{

int size = 0;
Map<String,Object> mapsussuccess=new HashMap<String,Object>();
List listnum=new ArrayList();
//String cdids="16384,16385,16386,16387,16388,16392,16393,16394,";
//String substring = cdid.substring(0, cdid.length()-1);
String[] split = cdid.split(",");

int length = split.length;
//Map map=new HashMap();
//map.put("cdid", cdid);
try {
int count=0;
for(int i=0;i<length;i++)
{
String string = split[i];
//System.out.println(string);
for(int j=0;j<string.length();j++)
{//List<CategoryLeafKeywords> findBykeywordId(String ckid);
//List<ComtyinfoDistinct> findByComtyinfoid(String cdid);
List<CategoryLeafKeywords> findByGoodsinfoselectID = clkdao.findBykeywordId(string);
Integer status = findByGoodsinfoselectID.get(j).getSpdier_status();
Integer id = findByGoodsinfoselectID.get(j).getId();
//System.out.println("status--->"+status);

if(status.equals(0)||status==0)
{
listnum.add(id);
size = listnum.size();
//System.out.println("listnum==>"+listnum);
//System.out.println("listnum==>"+size);
for(int z=0;z<size;z++)
{
Object object = listnum.get(z);
//lcygdao.update(object);
//cdao.updateDate(object);
clkdao.updateKeywords(object);
}

}
}

//Integer status = findByGoodsinfoselectID.get(i).getStatus();
//System.out.println("status==>"+status);
//
}
} catch (Exception e) {
// TODO Auto-generated catch block
return MessageUtils.errorMessages(1);
}
//cdao.updateDate(map);
mapsussuccess.put("linage", size);
mapsussuccess.put("code", 200);
mapsussuccess.put("message", "Congratulations, you made it!!!");
return JSON.toJSONString(mapsussuccess);



}


}
@RequestMapping("/gp")
public String getIp() throws UnknownHostException
{
 InetAddress addr = InetAddress.getLocalHost();
     System.out.println("Local HostAddress: "+addr.getHostAddress());
     String hostname = addr.getHostName();
     System.out.println("Local host name: "+hostname);
     return addr.getHostAddress();
}


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值