java高并发卖票例子

package com.github.pig.auth;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

        private List<String> tikets1 = new ArrayList<>();
    private Queue<String> tikets2 = new ConcurrentLinkedQueue<>();


    Test() {
        for (int i = 0; i < 100000; i++) {
            tikets1.add("票编号" + i);
        }
        for (int i = 0; i < 100000; i++) {
            tikets2.add("票编号" + i);
        }
    }

    private static StringBuffer sb = new StringBuffer();

    public void aa() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (this) {
            while (tikets1.size() > 0) {
                sb.append("销售了--" + tikets1.remove(0) + "\n");
            }
        }
    }

    public void bb() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (true) {

            String s = tikets2.poll();
            if (s == null) {
                break;
            } else {
                sb.append("销售了--" + s + "\n");
            }

        }
    }

    CountDownLatch latch = new CountDownLatch(10);

    public static void main(String[] args) {
        Test t = new Test();
        long start = 0L;

        List<Thread> lists = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
 //           Thread th = new Thread(t::aa);
            Thread th = new Thread(t::bb);
            th.start();
            lists.add(th);
            if (i == 9) {
                start = System.currentTimeMillis();
            }
            t.latch.countDown();//等待所有线程一起开始
        }

        //等待所有线程结束
        lists.forEach(o -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long end = System.currentTimeMillis();

        System.out.println(sb.toString());
        System.out.println(end - start + "ms");
    }


}

用队列效率最高 ,30ms

如果用synchronized要1000多ms


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值