zoukankan      html  css  js  c++  java
  • java 简单秒杀

    以下代码 不考虑多服务器

    限制线程池的大小 和队列的限制来实现

    package org.zhang;
    
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.Executors;
    import java.util.concurrent.SynchronousQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 单服务器用线程池实现秒杀的思路一
     * 
     * @author zhanghaijun
     * 
     */
    public class ExecutorsTest {
    
    	public static boolean flag = true; // 秒杀物品的标记
    
    	public static void main(String[] args) {
    		ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L,
    				TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
    		ThreadTest t1 = new ThreadTest("张三");
    		ThreadTest t2 = new ThreadTest("李四");
    		ThreadTest t3 = new ThreadTest("王五");
    		try {
    			pool.execute(t1);
    		} catch (Exception e) {
    			System.out.println(t1.getUserName() + "没有抢到");
    		}
    
    		try {
    			pool.execute(t3);
    		} catch (Exception e) {
    			System.out.println(t3.getUserName() + "没有抢到");
    		}
    
    		try {
    			pool.execute(t2);
    		} catch (Exception e) {
    			System.out.println(t2.getUserName() + "没有抢到");
    		}
    		pool.shutdown();
    	}
    
    }
    
    class ThreadTest extends Thread {
    
    	private String userName;
    
    	public ThreadTest(String userName) {
    		super();
    		this.userName = userName;
    	}
    
    	@Override
    	public void run() {
    		try {
    			Thread.sleep(200);
    			if (ExecutorsTest.flag) {
    				System.out.println(this.userName + "秒杀成功");
    				ExecutorsTest.flag = false;
    			}
    
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    	}
    
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    }
  • 相关阅读:
    CentOS7安装mysql
    centos 7 firewall(防火墙)开放端口/删除端口/查看端口
    CentOS7 FTP安装与配置
    处理nuget包太占用C盘
    windows下使用nginx
    SQL Server 设置新用户只能查看并访问特定数据库
    RPC框架
    RPC与REST
    Windows 环境下 Docker 使用及配置
    “远程调试监视器(MSVSMON.EXE)似乎没有在远程计算机上运行“的 解决方法
  • 原文地址:https://www.cnblogs.com/ouyangping/p/6880122.html
Copyright © 2011-2022 走看看