模拟高并发

这几天想鼓捣一下高并发,之前对并发数据一致性处理,使用的synchronized关键字,想试试lock,只不过效果不理想啊,

阶段一:用的lock.lock()和unLock()方法配合,只是保证了数据一致性,只不过会导致有的线程取不到结果

阶段二:使用lock.tryLock()和unLock()方法配合,当试图加锁失败的时候,再次调用业务方法,数据一致性和线程执行成功都得到了保证,但是执行时间有点长,和synchronized没法比啊(继续学习吧。。。)

 

使用synchronized关键字


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
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 HighConcurrenceBuy {
	private ReadWriteLock mReadWriteLock = new ReentrantReadWriteLock();
//	private Lock lock = mReadWriteLock.readLock();
	private Lock lock = new ReentrantLock();
	private People people;
	private Train train;

	public Train getTrain() {
		return train;
	}

	public void setTrain(Train train) {
		this.train = train;
	}
	
	public void buyTicket(People people) {//卖票
		synchronized (train) {
			int ticket = train.getTicket();
			people.setTicketNumber(ticket);
			ticket--;
			train.setTicket(ticket);
		}

//		if (lock.tryLock()) {
//			try {
//				int ticket = train.getTicket();
//				people.setTicketNumber(ticket);
//				ticket--;
//				train.setTicket(ticket);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} finally {
//				lock.unlock();
//			}
//		}else {
//			try {
//				Thread.currentThread().sleep(100);
//				buyTicket(people);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
	}
	
	public void refundable(People people) {//退票
		int ticket = train.getTicket();
		ticket++;
		train.setTicket(ticket);
	}

	public People getPeople() {
		return people;
	}

	public void setPeople(People people) {
		this.people = people;
	}
	
	private static int threadSize = 10000;
	private static CountDownLatch countDown = new CountDownLatch(threadSize);
	public static void main(String [] args) {

		Train train = new Train("东风",100000);
		HighConcurrenceBuy buy = new HighConcurrenceBuy();
		buy.setTrain(train);
		
		long startTime = System.currentTimeMillis();
		System.out.println("主线程start use:" + startTime);

		
		ExecutorService executor = Executors.newFixedThreadPool(2000);
		for(int i = 0;i<threadSize;i++) {
			
			People people = new People("王"+i);
			
			Callable<String> call1 = new Callable<String>() {
			    @Override  
			    public String call() throws Exception {  
			        Thread.sleep(100);
			        countDown.countDown(); 
					buy.buyTicket(people);

					System.out.println(Thread.currentThread().getName()+" user time "+(System.currentTimeMillis()-startTime));
			        //return the thread name executing this callable task  
			        return Thread.currentThread().getName();  
			    } 
				
			};
			FutureTask<String> future1 = new FutureTask<String>(call1);
			executor.execute(future1);
			
		}
		
		try {
			countDown.await();
			System.out.println("end use:" + (System.currentTimeMillis()-startTime));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

执行结果:

...
pool-1-thread-649 user time 1025
王9989买到了票编号:90001
东风号列车还剩:90000张票
pool-1-thread-1904 user time 1025

 

使用lock

执行结果:

...
东风号列车还剩:90001张票
pool-1-thread-691 user time 3361
东风号列车还剩:90000张票
王9629买到了票编号:90001
pool-1-thread-451 user time 3440

 

这让我情何以堪,继续学习吧,是不是哪里写的不对啊,望程序员的小哥哥小姐姐临幸

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值