这篇文章主要为大家展示了“java如何使用多线程模拟抢红包功能”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“java如何使用多线程模拟抢红包功能”这篇文章吧。
今天有朋友问我一道面试题,有5个人抢5个红包,可重复抢,用多线程程序实现,实现方式有多种,分享一下我的思路:应用了阻塞队列的特性。
/** * Created by zhanglinqiang on 2016/6/23. */ public class MyTest { public static void main(String[] args) throws InterruptedException { LinkedBlockingQueue<LuckyMoney> luckyMoneys = new LinkedBlockingQueue<>(); List<FutureTask> futureTasks = new ArrayList<>(); //准备抢红包 for (int i = 0; i < 5; i++) { FutureTask<Object> futureTask = new FutureTask<>(new CatchLuckMoney(luckyMoneys, "name" + i), null); new Thread(futureTask,"name"+i).start(); futureTasks.add(futureTask); } Thread.sleep(5);//确保抢红包线程准备就绪 Random random = new Random(100); //发5个红包 for (int i = 0; i < 5; i++) { luckyMoneys.put(new LuckyMoney("红包"+i, random.nextInt(100)+1)); } //等到红包抢完 while (!luckyMoneys.isEmpty()){ Thread.sleep(1); } //终止抢红包线程 for (FutureTask futureTask : futureTasks) { futureTask.cancel(true); } } } class CatchLuckMoney implements Runnable { public CatchLuckMoney(LinkedBlockingQueue<LuckyMoney> luckyMoneys, String name) { this.luckyMoneys = luckyMoneys; this.name = name; } private LinkedBlockingQueue<LuckyMoney> luckyMoneys; private String name; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { LuckyMoney redPackage = null; try { redPackage = luckyMoneys.take(); } catch (InterruptedException e) { // e.printStackTrace(); break; } System.out.println(name + "抢到了-->" + redPackage); luckyMoneys.remove(redPackage); } System.out.println("end>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+Thread.currentThread().getName()); } } class LuckyMoney { public LuckyMoney(String name, Integer money) { this.name = name; this.money = money; } private String name; private Integer money; @Override public String toString() { return "LuckyMoney{" + "name='" + name + '\'' + ", money=" + money + '}'; } }
运行效果:
Connected to the target VM, address: '127.0.0.1:8869', transport: 'socket' name3抢到了-->LuckyMoney{name='红包0', money=16} name4抢到了-->LuckyMoney{name='红包3', money=89} name0抢到了-->LuckyMoney{name='红包2', money=75} name1抢到了-->LuckyMoney{name='红包1', money=51} name3抢到了-->LuckyMoney{name='红包4', money=92} end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name0 end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name4 end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name3 Disconnected from the target VM, address: '127.0.0.1:8869', transport: 'socket' end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name1 end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name2 Process finished with exit code 0
以上是“java如何使用多线程模拟抢红包功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。